关于C#中Linq查询的应用
2012-03-08 14:54
162 查看
最近看了老赵关于《编程语言的发展趋势及未来方向》的博文,由于本人水平有限,还谈不能对编程语言的发展趋势发表自己的看法和见解,只是在工作之余,忙里偷闲,看看大牛们的博客,学习之余,也看到了一些关于自己平时开发中有用的东西,截取若干知识点放到这里,供自己平时学习或者工作中参考。
以下就是在这篇博文中看到的关于linq查询的一些运用:
例如,要筛选出单价大于20的产品,并对所属种类进行分组,并降序地列出每组的分类名称及产品数量。如果是用命令式的编程方式,则可能是这样的:
显然这些代码编写起来需要一点时间,且很难直接看出它的真实目的,换言之“What”几乎完全被“How”所代替了。这样,一个新的程序员必须花费一定时间才能理解这段代码的目的。但如果使用LINQ,代码便可以改写成:
这段代码更加关注的是“What”而不是“How”,它不会明确地给出过滤的“操作方式”,也没有涉及到创建字典这样的细节。这段代码还可以利用C# 3.0中内置的DSL,即LINQ查询语句来改写:
编译器会简单地将LINQ差距语句转化为前一种形式。这段代码只是表现出最终的目的,而不是明确指定做事的方式,这样便可以很容易地并行执行这段代码,如使用PINQ则几乎不需要做出任何修改。
Using the Code
1. Define the Person class that includes the ID, Name, and Age properties.
2. Build a list of Person to be used as the data source.
3. Use Linq to perform the query operation.
4. Use Linq to perform the Update operation.
5. Use Linq to perform the Order operation.
6. Use Linq to perform the Max, Min, Average queries.
7. Use Linq to count the Person whose age is larger than 20
截取此片段,只是想了解一下linq在.NET中的语法格式及简单运用,后续看到更高级运用会专门记录更新。
以下就是在这篇博文中看到的关于linq查询的一些运用:
例如,要筛选出单价大于20的产品,并对所属种类进行分组,并降序地列出每组的分类名称及产品数量。如果是用命令式的编程方式,则可能是这样的:
Dictionary<string, Grouping> groups = new Dictionary<string, Grouping>(); foreach (Product p in products) { if (p.UnitPrice >= 20) { if (!groups.ContainsKey(p.CategoryName)) { Grouping r = new Grouping(); r.CategoryName = p.CategoryName; r.ProductCount = 0; groups[p.CategoryName] = r; } groups[p.CategoryName].ProductCount++; } } List<Grouping> result = new List<Grouping>(groups.Values); result.Sort(delegate(Grouping x, Grouping y) { return x.ProductCount > y.ProductCount ? -1 : x.ProductCount < y.ProductCount ? 1 : 0; });
显然这些代码编写起来需要一点时间,且很难直接看出它的真实目的,换言之“What”几乎完全被“How”所代替了。这样,一个新的程序员必须花费一定时间才能理解这段代码的目的。但如果使用LINQ,代码便可以改写成:
var result = products .Where(p => p.UnitPrice >= 20) .GroupBy(p => p.CategoryName) .OrderByDescending(g => g.Count()) .Select(g => new { CategoryName = g.Key, ProductCount = g.Count() });
这段代码更加关注的是“What”而不是“How”,它不会明确地给出过滤的“操作方式”,也没有涉及到创建字典这样的细节。这段代码还可以利用C# 3.0中内置的DSL,即LINQ查询语句来改写:
var result = from p in products where p.UnitPrice >= 20 group p by p.CategoryName into g orderby g.Count() descending select new { CategoryName = g.Key, ProductCount = g.Count() };
编译器会简单地将LINQ差距语句转化为前一种形式。这段代码只是表现出最终的目的,而不是明确指定做事的方式,这样便可以很容易地并行执行这段代码,如使用PINQ则几乎不需要做出任何修改。
Using the Code
1. Define the Person class that includes the ID, Name, and Age properties.
class Person { public Person(int id, string name, int age) { this.id = id; this.name = name; this.age = age; } private int id; /// <summary> /// Person ID /// </summary> public int PersonID { get { return this.id; } set { this.id = value; } } private string name; /// <summary> /// Person name /// </summary> public string Name { get { return this.name; } set { this.name = value; } } private int age; /// <summary> /// Age that ranges from 1 to 100 /// </summary> public int Age { get { return this.age; } set { if (value > 0 && value <= 100) this.age = value; else throw new Exception("Age is out of scope [1,100]"); } } }
2. Build a list of Person to be used as the data source.
///////////////////////////////////////////////////////////////////// // Build the Person list that serves as the data source. // List<Person> persons = new List<Person>(); persons.Add(new Person(1, "Alexander David", 20)); persons.Add(new Person(2, "Aziz Hassouneh", 18)); persons.Add(new Person(3, "Guido Pica", 20)); persons.Add(new Person(4, "Chris Preston", 19)); persons.Add(new Person(5, "Jorgen Rahgek", 20)); persons.Add(new Person(6, "Todd Rowe", 18)); persons.Add(new Person(7, "SPeter addow", 22)); persons.Add(new Person(8, "Markus Breyer", 19)); persons.Add(new Person(9, "Scott Brown", 20));
3. Use Linq to perform the query operation.
///////////////////////////////////////////////////////////////////// // Query a person in the data source. // var Todd = (from p in persons where p.Name == "Todd Rowe" select p).First(); // [-or-] // Use extension method + lambda expression directly //var Todd = persons.Where(p => p.Name == "Todd Rowe").First(); Console.WriteLine("Todd Rowe's age is {0}", Todd.Age);
4. Use Linq to perform the Update operation.
///////////////////////////////////////////////////////////////////// // Perform the Update operation on the person's age. // Todd.Age = 21; Console.WriteLine("Todd Rowe's age is updated to {0}", (from p in persons where p.Name == "Todd Rowe" select p).First().Age);
5. Use Linq to perform the Order operation.
///////////////////////////////////////////////////////////////////// // Sort the data in the data source. // Order the persons by age var query1 = from p in persons orderby p.Age select p; Console.WriteLine("ID\tName\t\tAge"); foreach (Person p in query1.ToList<Person>()) { Console.WriteLine("{0}\t{1}\t\t{2}", p.PersonID, p.Name, p.Age); }
6. Use Linq to perform the Max, Min, Average queries.
///////////////////////////////////////////////////////////////////// // Print the average, max, min age of the persons. // double avgAge = (from p in persons select p.Age).Average(); Console.WriteLine("The average age of the persons is {0:f2}", avgAge); double maxAge = (from p in persons select p.Age).Max(); Console.WriteLine("The maximum age of the persons is {0}", maxAge); double minAge = (from p in persons select p.Age).Min(); Console.WriteLine("The minimum age of the persons is {0}", minAge);
7. Use Linq to count the Person whose age is larger than 20
///////////////////////////////////////////////////////////////////// // Count the persons who age is larger than 20 // var query2 = from p in persons where p.Age > 20 select p; int count = query2.Count(); Console.WriteLine("{0} persons are older than 20:", count); for (int i = 0; i < count; i++) { Console.WriteLine(query2.ElementAt(i).Name); }
截取此片段,只是想了解一下linq在.NET中的语法格式及简单运用,后续看到更高级运用会专门记录更新。
相关文章推荐
- C#应用中的LINQ 查询语言
- Jqgrid在C#下的应用,使用LINQ查询结果集
- 关于linq to sql调用存储过程,出现"无法枚举查询结果多次"的问题
- C#使用XmlDocument操作XML进行查询、增加、修改、删除、保存应用的实例
- C#语法之Linq查询基础二
- Linq关于空值的查询问题
- C#程序中使用LINQ to XML来查询XML格式数据的实例
- C#关于HttpClient的应用(二):融云IM集成
- C#中Linq查询基本操作
- LINQ 查询语法与方法语法 (C#)
- SQL分页存储过程和C#中linq分页查询方法
- 子查询 关于子查询应用外表的字段 2008.10.18 oracle
- C#学习常用的命名空间---System.Data.Linq(语言集成查询)
- C#如何使用LINQ查询数据(一)
- 关于SQL连接 加条件查询的LINQ表达式写法
- LINQ的数据库查询应用
- 关于c#静态方法和实例方法的辨析和应用
- C#中关于System.Diagnostics.Process的应用(转)
- 关于LINQ(语言集成查询)的一些学习笔记
- 关于C#中文本模板(.tt)的简单应用