Wednesday, December 1, 2010

Use Linq Query and Extension Method two styles to get IEnumerable Collections

for example there is a IEnumerable Object, we take an Array as an example:

string [5] arr=new string[5]{"bolt","create","eat","bat","boat"};

Use normal Linq query, that is

var q=from str in arr
where str.StartWith("b")
order by str.Length
select str;

Here we get an IEnumerable q;

We can also use Extension method for the class which implements IEnumerable interface.

var q=arr.Where(str=>str.StartWith("b"))
.OrderBy(str=>str.Length);

Notice the extension method Where(), OrderBy(), the parameter should be an predefined delegate --Predicate to call a function with boolean returned value.

As we know, Predicate, Action, Func can all be written in lambda expression.

So use the extension method, the format should be like: arr.Where(str=>str.StartWith("b")).

Let's go to definition of Where extension method:
public static IEnumerable Where(this IEnumerable source, Func predicate);

No comments: