How to Use LINQ OfType

The LINQ OfType operator can be used to return objects of a certain type from an array. For example, if we have an array of objects which contains both strings and numbers, we can use the LINQ OfType operator to return only strings or only numbers

LINQ OfType Example – Return Only Strings

object[] goop = { "string1", 2, 5, "string2", "string3" };

var onlyStrings =
  from g in goop.OfType<string>()
  select g;
foreach (var item in onlyStrings)
  Console.WriteLine(item);

The result will be

string1
string2
string3

 
I can modify the query to extract only integers which will look like this:

LINQ OfType Example – Return Only Integers

var onlyStrings =
  from g in goop.OfType<int>()
  select g;

With a result of:

2
5


While it is not good practice to have an array which contains strings and integers, we could be working with some legacy code. The LINQ OfType operator will come in handy in such situations.

GD Star Rating
loading...
GD Star Rating
loading...
  • Share/Bookmark

No related posts.

Related posts brought to you by Yet Another Related Posts Plugin.

Leave a Reply