Application of Linq query in C #

Source: Internet
Author: User

I recently read Lao Zhao's blog on "development trends and future directions of programming languages". Due to my limited level, I still cannot express my own views and opinions on the development trends of programming languages, just in my spare time, I was so busy. I looked at the blogs of the scalpers and learned some useful things about my usual development. I cut some knowledge points and put them here, for your reference in your daily study or work.

The following are some of the usage of linq queries in this blog post:

For example, you need to filter out products with a unit price greater than 20, group the product categories, and list the category names and product quantities of each group in descending order. If you use imperative programming, it may be like this:

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;});

Obviously, it takes a little time to write the code, and it is difficult to directly see its real purpose. In other words, "What" is almost completely replaced by "How. In this way, a new programmer must spend some time to understand the purpose of this Code. However, if you use LINQ, the code can be rewritten:

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() });

This Code focuses more on "What" rather than "How". It does not explicitly provide the "Operation Method" for filtering, nor involves details such as creating dictionaries. This code can also be rewritten using the built-in DSL in C #3.0, that is, the LINQ query statement:

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() };

The compiler will simply convert the LINQ Gap statement into the previous form. This piece of code only shows the ultimate goal, rather than specifying the way to do things, so that you can easily execute this piece of code in parallel. If PINQ is used, there is almost no need to make any changes.

 

Using the Code

1. Define the Person class that includes des 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 persons 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);        } 

 

After intercepting this clip, I just want to know the syntax format and simple usage of linq in. NET. Later, I will see more advanced usage records for updates.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.