- Lambda表达式在C#3.0加入,它是一个匿名函数,可用于创建委托或者表达式树类型,运算符为=>,读作”goes to”,=>左侧是变量,右侧是表达式,变量类型可以自动推导
- Linq查询操作由三个不同操作组成:示例代码:
- 获取数据源,数据源可以使Xml,SQL数据库,Ado.net数据集,.Net集合中的数据等
- 创建查询,但并没有执行查询,只是用一个变量存储查询,查询表达式包含三个字句:执行查询:使用foreach语句循环访问查询变量时才会真正执行查询,使用Count,Max,Average,First也会立即执行查询,这些语句会隐式调用foreach
- from:指定数据源
- where:指定filter
- select:指定返回数据
-
[TestClass] public class XmlLinqTest { private static XElement doc; [ClassInitialize] public static void Initialize(TestContext context) { doc = XElement.Load("Books.xml"); } [TestMethod] public void QueryBook_Id_ReturnBook() { IEnumerable<XElement> books=from el in doc.Elements() where el.Attribute("id").Value.Equals("1") select el; XElement book = books.First(); Assert.AreEqual(book.Attribute("id").Value, "1"); Assert.AreEqual(book.Attribute("name").Value,"Linq"); Assert.AreEqual(book.Attribute("author").Value,"Tom"); } }
<?xml version="1.0" encoding="utf-8" ?> <Books> <Book id="1" name="Linq" author="Tom" /> <Book id="2" name="Lambda" author="Jerry" /> </Books>
- 查询关键字:查询语法在编译时被转换为方法调用,这些方法被称为standard query operators,包括Where,Select,GroupBy,Join,Max,Average等(都是扩展方法),可以直接调用这些方法替代查询语法
- orderby:对返回的数据进行排序
- group:按指定的键对结果进行分组,如果要对分组的结果进行操作可以使用into创建一个可以使用的查询符
- 示例代码:
// custQuery 的类型是IEnumerable<IGrouping<string, Customer>>
// IGrouping是group.. by语句的返回类型
var custQuery = from cust in customers group cust by cust.City into custGroup where custGroup.Count() > 2 orderby custGroup.Key select custGroup; - join:联接,join字句接受两个数据源作为输入,只能执行等联接,也就是只能基于两个键之间的相等关系进行匹配,分为如下几种:
- inner join:
- group join:含有into字句,将会产生一个分组序列,该序列将左侧数据源中的元素与右侧数据源中的一个或多个元素相关联,如果右侧没有与左侧元素匹配的元素,则会产生一个空的集合
- left outer join:在group join中使用DefaultEmpty方法,用于指定没有匹配时,左侧元素对应的元素,这样左侧数据源中的每个元素都会有对应的集合
- 示例代码:
<?xml version="1.0" encoding="utf-8" ?> <Authors> <Author id="1" name="Tom" /> <Author id="2" name="Jerry"/> <Author id="3" name="Jack"/> </Authors> <?xml version="1.0" encoding="utf-8" ?> <Books> <Book id="1" name="Linq" authorId="1" /> <Book id="2" name="Lambda" authorId="2" /> <Book id="3" name="C#" authorId="1" /> </Books>
//BooksGroup是Books xml中满足条件的element的集合var group = from author in authors.Elements() join book in books.Elements() on author.Attribute("id").Value equals book.Attribute("authorId").Value into BooksGroup where author.Attribute("id").Value.Equals("1") select new { Author = author.Attribute("name").Value, authorBooks = BooksGroup };
- select:生成查询结果
- let:使用新的变量存储子表达式的结果,可供后面语句继续使用
-
int[] numbers = { 5, 10, 8, 3, 6, 12}; //Query syntax: IEnumerable<int> numQuery1 = from num in numbers where num % 2 == 0 orderby num select num; //Method syntax: IEnumerable<int> numQuery2 = numbers.Where(num => num % 2 == 0).OrderBy(n => n);
- https://blogs.msdn.microsoft.com/wesdyer/2008/01/10/the-marvels-of-monads/
转载于:https://www.cnblogs.com/phenixyu/p/3975179.html