What is OfType operator in LINQ?

OfType operator in LINQ

OfType operator is used to return objects of a certain type. For example if we have an array of objects which contains strings, decimal, float and numbers or any other. We can use OfType operator to extract only strings or any particular type of values.

Here is an example to fetch the string values from an array of objects. See below,

private void Form1_Load(object sender, EventArgs e)
object[] values = {"test1",45,'c',"test2",34.67,12/12/2009,"test3",4.0,4.4f};
var strings = values.OfType();
int top = 10;
foreach (var s in strings)
Label lbl = new Label();
lbl.Top = top;
top = top + 30;
lbl.Text = s;

You just copy the above code in to Form_Load and run the solution. There will be shown the string values.


No comments: