Collections and IEnumerable
Though LINQ to Objects can be used to query several C# types, it cannot be used against all your in-process data sources. Those that can be queried all support the IEnumerable
All of the collections in the System.Collections.Generic namespace support the IEnumerable
public class List<T> : IList<T>, ICollection<T>, IEnumerable<T>, IList, ICollection, IEnumerableYou will find IEnumerable
LINQ to Objects and IEnumerable
Consider the following simple LINQ query:
List<int> list = new List<int> { 1, 3, 2 };
// The LINQ Query expression
var query = from num in list
where num < 3
select num;
foreach (var item in query)The type IEnumerable
{
Console.WriteLine(item);
}
* The query expression has a data source called list which implements IEnumerable
* The query expression returns an instance of IEnumberable
Every LINQ to Objects query expression, including the one shown above, will begin with a line of this type:
from x in y
In each case, the data source represented by the variable y must support the IEnumerableThe same query shown here could also be written as follows:
IEnumerable<int> query = from num in list
where num < 3
select num;
This code makes explicit the type of the variable returned by this query. As you can see, it is of type IEnumerable
int number = (from num in listIn this case the query returns an integer specifying the number of items in the list created by this query. LINQ queries that return a simple type like this are an exception to the rule that LINQ to Objects queries operate on class that implement IEnumerable
where num < 3
select num).Count();
Composable
The fact that LINQ to Objects queries both take and return IEnumerable
List<int> list = new List<int> { 1, 3, 2 };Here the results of the first query are used as the data source for the second query, and the results of the first two queries are both used as data sources for the third query. If you print out the results of query3 with a foreach loop you get the numbers 3 and 4. Though it is not important to the current subject matter, you might have fun playing with the code to understand why these values are returned.
var query1 = from num in list
where num < 3
select num;
var query2 = from num in query1
where num > 1
select num;
var query3 = from num1 in query1
from num2 in query2
select num1 + num2;
Summary
By now it should be clear to you that IEnumerable
The next logical question would be to ask why this type plays such a key role in LINQ to Objects. One simple answer would be that the creators of LINQ decided that it should be so, and hence it is so. But one can still ask why they picked this particular type. What is it about IEnumerable

没有评论:
发表评论