Sunday, 11 March 2012

What is OfType extension Method how to use?


Yes, In Linq(language Integriated Query) we have may extension to work with query based operations.
In linq all clauses are  are defined as Extension methods. Like where clause -àwhere extension…ect
Ex:
Linq to Objects
Quering an object using linq is called linq to object.
Prepare an object then query from linq style.
static class Enumerable
{
public static IEnumerable<TResult> OfType<TResult>(this IEnumerable source);
}
ArrayList is one non-generic collection so this collection contains all types of data.

ArrayList arr = new ArrayList();
           arr.Add(5);              //int
           arr.Add("efgh");     //string
           arr.Add(10);           // int
           arr.Add("mnop");  // preparing an object
          var x = from n in arr.OfType<int>()  where n == 10 select n;
          Console.WriteLine(x);


So we have to

 Filters the elements of an System.Collections.IEnumerable based on a specified type.
Like
          OfType<int> then filter the specified value from all int types.
          OfType<string> then filter the specified value from all string types.
           OfType<double> then filter the specified value from all double types.
………………..ect.

Coming to Generic Collections Like List<T> types not required this OfType<Tsoruce> methods
Why because which accepts all the elements same type.

List<int> arrlist = new List<int>();
           arrlist.Add(10);
           arrlist.Add(20);
           arrlist.Add(30);
  var y = from m in arrlist where m == 10 select m;
not requried OfType<TResult>() method here because of list is Strongly typed or Generic Collecton.

No comments:

Post a Comment