LINQ basics


  1. Obtain the data sources(s)
  2. Create the query
    1. Declare variable var query = the following
    2. From variable Name in obtained data Source //Declaration
    3. Where variable name. Property == or > or < or any operator against any value // criteria and filtering
    4. Orderby variable name. Property, variable name. Property //sorting
    5. Select (variable name or variable name * 10 (any expression) or new { property1= val1 , property2 = val2 } (anonymous type) // projection
  3. Execute the query
    1. ToList() //by calling
    2. ToArraay() //by calling
    3. Foreach and access the query result

Example

[sourcecode language=”csharp”]

var files = new DirectoryInfo(@"c:\").GetFiles(); //Obtain the data sources(s)
var query = from file in files //Create the query //Declaration
where file.Length > 0 // criteria and filtering
orderby file.Name, file.Length //sorting
select new // projection
{
Name = file.Name,
Length = file.Length,
CreatedDate = file.CreationTime
};
var my = query.ToList(); //Execute the query

//or

foreach (var myFileInfo in query) //another Execute of the query
{
Console.WriteLine(myFileInfo.Name);

}
[/sourcecode]


Share This: