What's the meaning of this:
IEnumerable<int> query = from num in list
where num < 3
select num;
Is this an object as IEnumerable<T>?
Can anyone please describe this?
What's the meaning of this:
IEnumerable<int> query = from num in list
where num < 3
select num;
Is this an object as IEnumerable<T>?
Can anyone please describe this?
You know normal method syntax, right? Things like list.Add(10)
. Some smart minds at Microsoft noted that there are similarities in many collections and lists. People might like to do things like selecting certain values and summing values that should work on all collections, without each and every collection providing a method for it.
Therefore they introduced extension methods, that are methods that are only defined once but can be applied to all objects of a certain type, such as collections. Examples are list.Where
and list.Sum
. To use extension methods, you have to add the namespace in which they are defined. The Where
extension method takes a lambda expression which is executed on each and every element of the collection.
Lets say that you have some list of integers:
List<int> list = new List<int>();
list.Add(-1);
list.Add(0);
list.Add(1);
list.Add(2);
list.Add(3);
list.Add(4);
Then, where I previously would have to write the following code to get only those integers less than three:
List<int> query = new List<int>();
foreach(var nr in list)
{
if (nr < 3)
query.Add(nr);
}
Now, using extension methods, I can write it like this:
IEnumerable<int> query = list.Where(nr => nr < 3);
When enumerated, query
will only return the integers from list
that are less than three. These extension methods are part of LINQ, the Language Integrated Query.
However, to make LINQ easier to use, they devised a new syntax. With this new syntax, LINQ is easier to read and write.
IEnumerable<int> query = from nr in list
where nr < 3
select nr;
The compiler takes the new syntax and translates it to the previously mentioned code that includes the Where
method. You see, its just syntactic sugar to make working with collections easier.
The IEnumerable<int>
interface is a generic interface for any object that can be enumerated. The simplest form of enumeration is doing foreach
on the object, and it returns all integers it contains, one by one. So, the LINQ query returns some object, but you don't know exactly the type. But you know it can be enumerated, and this makes it very useful.
It's a linq equivalent of say
IEnumerable<int> GetLessThanThree(IEnumerable<int> list)
{
foreach(int num in list)
{
if (num < 3)
{
yield return num
}
}
}
or if you haven't met yield yet
IEnumerable<int> GetLessThanThree(IEnumerable<int> list)
{
List<int> result = new List<int>();
foreach(int num in list)
{
if (num < 3)
{
result.Add(num);
}
}
return result;
}