about linq, IEnumerable<T> and Lambda expression

T

Tony Johansson

Hello!

I have this linq query below with two lambda expressions.

If I look at the documentation for Where operator it says.
public static IEnumerable<T> Where<T>(
this IEnumerable<T> source,
Func<T, bool> predicate);

In my case where I have a Where operator it will match the second row that
says
Func<T, bool> predicate
In my where operator, T is an int and I return bool.

Now to my question what does it mean with the first row that says
* this IEnumerable<T> source *
and what can it be used for ?


int[] nums = new int[] {6,2,7,1,9,3};
IEnumerable<int> numsLessThenFour = nums
..Where(i => i<4)
..OrderBy(i => i);

foreach(int number in numsLessThenFour )
Console.WriteLine(number);

//Tony
 
P

Peter Morris

Now to my question what does it mean with the first row that says
* this IEnumerable<T> source *

IEnumerable<T> source

This is the source, in your case "nums"

But, instead of you having to write

SomeStaticClassName.Where(nums, someFunc)

the "this" statement makes "Where" an extension method on anything that
implements IEnumerable<T> (which an array of byte does), so you can instead
write

nums.Where(someFunc)

which is the same as

Where(nums, someFunc)
 
M

Martin Honnen

Tony said:
If I look at the documentation for Where operator it says.
public static IEnumerable<T> Where<T>(
this IEnumerable<T> source,
Func<T, bool> predicate);

Now to my question what does it mean with the first row that says
* this IEnumerable<T> source *
and what can it be used for ?


public static IEnumerable<T> Where<T>(
this IEnumerable<T> source,
means the Where method (as other LINQ methods) is implemented as an
extension method.

If you look at the methods of the IEnumerable<T> interface
http://msdn.microsoft.com/en-us/library/ckzcawb8.aspx
then you will see that only GetEnumerator is implemented as a "normal"
methods while all the LINQ query methods are implemented as extension
methods. With C# and VB.NET you can call extension methods like normal
instance methods.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top