LINQ or Language
Integrated Query gives the capability to query objects and C# allows two distinctive ways to achieve this – You can either use LINQ query operators model or LINQ extension methods model with Lamba expressions on Func<> delegate.
We have -
LINQ to Objects – Objects in memory eg:
Collections
·
LINQ to Entities – eg: Databases
·
LINQ to XML – eg: XML
·
LINQ to Data sets – ADO.NET data sets
Example
We have a Book class and a Book repository that will hold a
list of Books. In the main program we will use LINQ to so some operations on
the Book list.
Book
public class Book
{
public string Title { get; set; }
public float Price { get; set; }
}
BookRepository –
returns a list of predefined Books
public class BookRepository
{
public IEnumerable<Book> GetBooks()
{
return new List<Book>
{
new Book() { Title = "ABC", Price = 20.50f },
new Book() { Title = "DE", Price = 30},
new Book() { Title = "RE", Price = 20},
new Book() { Title = "YE", Price = 50},
new Book() { Title = "WEE", Price = 34},
new Book() { Title = "SDE", Price = 40}
};
}
}
Main program
class Program
{
static void Main(string[] args)
{
var books = new BookRepository().GetBooks();
//LINQ Query Operators
var cheapBooks =
from b in books
where b.Price > 30
orderby b.Title
select b.Title;
//LINQ Extension methods
var cheaperBooks = books
.Where(b => b.Price > 30)
.OrderBy(b => b.Title)
.Select(b => b.Price);
//returns one or 0 items.Single returns 1 and
only1 item
var singleBook = books.
SingleOrDefault(b => b.Title
== "WEE");
//returns first item from the match
var firstItem = books.
FirstOrDefault(b => b.Price > 30);
//returns last item from the match
var lastItem = books.
LastOrDefault(b => b.Price > 30);
//return skip some and next few
var skipItems = books.
Skip(2).Take(3);
//Count items
var cnt = books.Count();
//Max, Min, Sum
var max = books.
Skip(2).Take(4).Max(b => b.Price);
//var item = books.Aggregate(b => b.Price);
foreach (var i in cheapBooks)
{
Console.WriteLine(i);
//Console.WriteLine(i.Title);
}
foreach (var i in cheaperBooks)
{
Console.WriteLine(i);
//Console.WriteLine(i.Title);
}
Console.WriteLine(singleBook.Title);
Console.WriteLine(firstItem.Title);
Console.WriteLine(lastItem.Title);
foreach (var i in skipItems)
{
Console.WriteLine(i.Title);
//Console.WriteLine(i.Title);
}
Console.WriteLine(cnt);
Console.WriteLine(max);
}