Introduction to LINQ Queries (C#)
In a LINQ query, you are always working with objects. You use the same basic coding patterns to query and transform data in XML documents, SQL databases, ADO.NET Datasets, .NET collections, and any other format for which a LINQ provider is available.
All LINQ query operations consist of three distinct actions:
-
Obtain the data source.
-
Create the query.
-
Execute the query.
class IntroToLINQ
{
static void Main()
{
// The Three Parts of a LINQ Query:
// 1. Data source.
int[] numbers = new int[7] { 0, 1, 2, 3, 4, 5, 6 };
// 2. Query creation.
// numQuery is an IEnumerable<int>
var numQuery =
from num in numbers
where (num % 2) == 0
select num;
// 3. Query execution.
foreach (int num in numQuery)
{
Console.Write("{0,1} ", num);
}
}
}
Note:
1. data source type must be IEnumerable<T> or deprived type IQueryable<T> to use LINQ. e.g. xml file don't support IEnumerable<T> type, we need to manually create a type
// Create a data source from an XML document. // using System.Xml.Linq; XElement contacts = XElement.Load(@"c:\myContactList.xml");
2. step2 has not retrieved data from data source, step3 does. that's because this is deferred execution. it executes in foreach statement
3. to force execute immediately, call tolist<T> or toarray<T>, or execute foreach(which not cache the result in one object)
You can also force execution by putting the foreach loop immediately after the query expression. However, by calling ToList or ToArray you also cache all the data in a single collection object.
List<int> numQuery2 =
(from num in numbers
where (num % 2) == 0
select num).ToList();
----------------------------------------------------------------------
// or like this: // numQuery3 is still an int[]
var numQuery3 = (from num in numbers where (num % 2) == 0 select num).ToArray();
----------------------------------------------------------------------
IEnumerable<Customer> customerQuery =
from cust in customers
where cust.City == "London"
select cust;
foreach (Customer customer in customerQuery)
{
Console.WriteLine(customer.LastName + ", " + customer.FirstName);
}

浙公网安备 33010602011771号