LINQ
What is LINQ
Stands for: Language Integrated Query
Gives you the ability to query objects.
You can query:
- Objects in memory, eg collections (LINQ to Objects)
- Databases (LINQ to Entities)
- XML (LINQ to XML)
- ADO.NET Data Sets (LINQ to Data Sets)
You can chain LINQ methods like with jQuery.
LINQ Extentions Methods (LINQ to objects)
var cheapBooks = books
.Where(b => b.Price < 10)
.OrderBy(b => b.Title)
.Select(b => b.Title);
Average |
var avg = books.Average(b => b.Price); Returns the average price. |
Count |
var count = books.Count(); |
First |
.First(); Used to get the first object in a collection. .First(b => b.Title == "Book Name"); If you supply a predicate (filter), it will return the first object matching your predicate. (In this case the first book with Title 'Book Name') |
FirstOrDefault |
.FirstOrDefault(b => b.Title == "Book Name"); If no match is found this will return the default value (in this case null) |
Last |
.First(); Used to get the last object in a collection. .Last(b => b.Title == "Book Name"); If you supply a predicate (filter), it will return the last object matching your predicate. (In this case the last book with Title 'Book Name') |
LastOrDefault |
.LastOrDefault(b => b.Title == "Book Name"); If no match is found this will return the default value (in this case null) |
Max |
var priceHigh = books.Max(b => b.Price); Will return book with highest price. |
Min |
var priceMin = books.Min(b => b.Price); Will return book with lowest price. |
OrderBy | books.OrderBy(b => b.Title) - Order books by Title |
Single |
Return only a single item in the list. .Single(b => b.Title == "ASP.NET MVC"); If there is no objects that matches this criteria, an exception error will occur. |
SingleOrDefault |
Return only a single item in the list, but if no matching condition then default will be returned. .SingleOrDefault(b => b.Title == "ASP.NET MVC"); |
Skip |
Use for paging data. Used in conjunction with Take. .Skip(2) Skip 2 objects |
Sum |
var priceTotal = books.Sum(b => b.Price); Will return sum of prices for all books. |
Take |
Use for paging data. Used in conjunction with Skip. .Take(3); Take 3 objects |
Where | books.Where(b => b.Price < 10) - Return all books with price lower than 10 |
Select |
Use for projections or transformation. .Select(b => b.Title) |
LINQ Query Operators
Always start with the 'from' and ends with the 'select'
var cheapBooks =
from b in books
where b.Price < 10
orderby b.Title
select b.Title;