Condividi tramite


LINQ: OfType Query Operator

 

 

LINQ comes with the OfType<T> query operator, through which we can filter the required object type from a heterogeneous array.

Suppose below is the scenario where we have array with various types but will only retrieve the string type. Here we go with ease of life,

using System;

using System.Collections.Generic;

using System.Text;

using System.Query;

using System.Xml.XLinq;

using System.Data.DLinq;

namespace LINQConsoleApplication1_Oct11

{

    class Program

    {

     static void Main(string[] args)

        {

            object[] numbers = {"Wriju", 28, 12/12/2006, 3.3f, 1, "Tupur", 8.0};

            var strs = numbers.OfType<string>();

            Console.WriteLine("The list of friends..");

            Console.WriteLine("==========================");

            foreach(var s in strs)

            {

                Console.WriteLine(s);

            }

            Console.ReadKey();

        }

    }

}

Output will look like

The list of friends..

==========================

Wriju

Tupur

Namoskar

Comments

  • Anonymous
    May 01, 2008
    Nice sample, simple and easy to understand.

  • Anonymous
    September 10, 2008
    Nice sample was searching for a similar thing. Thanks.

  • Anonymous
    April 22, 2010
    Brilliant, I use this, shame books only give exmaples that cast and oftype are for use with legacy collections.

  • Anonymous
    April 21, 2011
    Add null as one of the array element to make clear how OfType<T> works with nulls (now it filters them out)

  • Anonymous
    February 21, 2012
    Is there a LINQ operator for it? Do you know of a list of all the linq operators built-in C# (such as where, join, select etc.)?