查询一个对象集合中满足条件的对象。
internal class Book
{
public Book(string title, int authorId, int year)
{
Title = title;
AuthorId = authorId;
PublishYear = year;
}
public string Title { get; set; }
public int AuthorId { get; set; }
public int PublishYear { get; set; }
public override string ToString()
{
return string.Format("{0} - {1}", Title, PublishYear);
}
}
internal class Author
{
public Author(int id, string firstName, string lastName)
{
Id = id;
FirstName = firstName;
LastName = lastName;
}
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public void Foo()
{
List<Book> books = new List<Book>
{
new Book("Le Rhin", 1, 1842),
new Book("Les Burgraves", 1, 1843),
new Book("Napolé§|on le Petit", 1, 1852),
new Book("Les Châtiments", 1, 1853),
new Book("Les Contemplations", 1, 1856),
new Book("Les Misé§|rables", 1, 1862)
};
List<Author> authors = new List<Author> {new Author(1, "Victor", "Hugo")};
}
}
最简单的LINQ查询:
var allBooks = from book in books select book;
foreach (Book book in allBooks)
{
Console.WriteLine(book.ToString());
}
按顺序显示:
var ordered = from book in books
orderby book.Title descending
select book;
var ordered = from book in books
orderby book.PublishYear, book.Title descending
select book;
LINQ 提供了 where子句(where clause),可以根据给定的条件过滤集合中的对象
var before1850 = from book in books
where book.PublishYear < 1850
select book;
var dateRange = from book in books
where book.PublishYear >= 1850
&& book.PublishYear <= 1855
select book;
选择某些特定的列:
var justTitlesAfter1850 = from book in books
where book.PublishYear > 1850
select book.Title;
var withAuthors = from book in books
join author in authors on book.AuthorId equals author.Id
select
new
{
Book = book.Title,
Author = string.Format("{0} {1}", author.FirstName, author.LastName)
};
Console.WriteLine("Join with authors:");
foreach (var bookAndAuthor in withAuthors)
{
Console.WriteLine("{0}, {1}", bookAndAuthor.Book, bookAndAuthor.Author);
}