Tuesday, August 16, 2011

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

No comments:

Post a Comment