LINQ - 查询对象集合
2013-01-29 13:08
351 查看
查询一个对象集合中满足条件的对象。
最简单的LINQ查询:
按顺序显示:
LINQ 提供了 where子句(where clause),可以根据给定的条件过滤集合中的对象
选择某些特定的列:
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); }
相关文章推荐
- LINQ学习笔记(9) LINQ to Objects---查询内存中对象的集合
- 用LINQ在集合中查询特定对象
- Linq集合查询出现无法将类型为“System.Int32”的对象强制转换为类型“System.String”异常
- 用LINQ在集合中查询特定对象
- 回收站查询,linq对对象集合的使用
- LINQ查询对象集合
- 回收站查询,linq对对象集合的使用
- (转)Hibernate中关于多表连接查询hql 和 sql 返回值集合中对象问题
- Oracle 之——子查询 DDL DML 集合 及其他数据对象
- Linq 学习(7) 延迟执行 & 查询非泛型集合
- 【Java EE 学习 28 上】【oracle学习第二天】【子查询】【集合运算】【几种数据库对象】
- Hibernate 通过批量ID进行查询所对应的对象集合
- Mybatis查询语句返回对象和泛型集合
- 神奇的LINQ ---可以通过对象来查询数据
- 开发:异常收集之 ibatis查询集合有多个对象,但是对象都为空
- spring-mongo-template中对内嵌集合对象 不定参数的查询
- 开发:异常收集之 ibatis查询集合有多个对象,但是对象都为空
- C# LINQ查询之对象
- C#3.0(六)-Linq to object(3)查询方法操作集合
- C#linq和lamda两种写法返回的集合中的对象元素引用情况不同,循环计算值要小心