LINQ study notes
1. LINQ concept:
LINQ stands for language integrated Query. You can retrieval datafrom various sources (SQL database, list, object, xml, array) by just using LINQ,instead of different languages.
2. Basic grammar:
<code>
Var queryResult =
From nin names
Wheren.StartWith(“S”)
orderbyn descending
Selectn;
</code>
var keyword: to declare a variable without figuring out the type of it.The compiler will infer the type for it based on the result type.
In this example, ‘names’ is the data source for this query. The datasource must implement theIEnumerableinterface.
Deferred Execution: The query result variable will only save the plan of retrievaluntil the result is visited.
Lambda operator ( => ):read as goes to or such that.
3. AdvancedOperation keywords:
Order by:
Orderbyn or names.OrderBy(n=>n)
Orderbyn descending or names.OrderByDescending(n=>n)
Orderbyobj.a1, obj.a2, obj.a3 or objs.Orderby(…).ThenbyDescending(…).Thenby(…).select(…)
Mathmethod:
queryResult.Count(),qR.Max(), qR.Min(), qR.Average(), qR.Sum(n=>(long)n)
While retrieval from object and hope to only returnparticular member variables of object:
……..select object.id=1 or objs.select(obj => obj.id = 1
……. Selectnew {obj.a1, obj.a2, obj.a3 } or objs.select(obj => new { obj.a1, obj.a2, obj.a3}
Distinct:
Objs.select(obj=>……).distinct();
Anyand All: to check whether the particular record or all records meet therequirement and return a Boolean result:
bool
boolanyUSA = objs.Any( obj => obj.country == “USA”)
bool allUSA = objs.All ( obj=>obj.country == “USA”);
Groupby:
Group objby obj.Region into cg
Grouping therecords by Region and save the group name as cg.
TOP:
Foreach( var item in objs.Take(5)){……}
Do operation ontop five records. Remember to order the records first, if it is necessary.
Foreach(var item in objs.Skip(5)){…..}
Ignore the top five records while doing operation on the result group.
First and FirstOrDefault:
qs.First( obj=>obj.Region == “Africa”);
qs.FirstOrDefault(obj=>obj.Region == “Africa”);
These twostatement both return the first record in the records set. I believe theFirstOrDefault is better in most of cases, as you don’t need to worry about theerror processing if the result is null;
4. Invoke procedure using LINQ to SQL
Just simplely use the precedure name as a function will make it. For example:
List<obj> = dbContext.StoredProcedure1();