关于C#中Linq查询的应用
最近看了老赵关于《编程语言的发展趋势及未来方向》的博文,由于本人水平有限,还谈不能对编程语言的发展趋势发表自己的看法和见解,只是在工作之余,忙里偷闲,看看大牛们的博客,学习之余,也看到了一些关于自己平时开发中有用的东西,截取若干知识点放到这里,供自己平时学习或者工作中参考。
以下就是在这篇博文中看到的关于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中的语法格式及简单运用,后续看到更高级运用会专门记录更新。