linq syntax base using examples

  • 2020-06-01 10:55:37
  • OfStack

With the LINQ technique, we can query any form of data using a syntax similar to SQL. From a technical point of view, LINQ defines about 40 query operators, such as from, select, in, where, group by, orderby... You can write query statements using these operators.

Do software, always think about how to better reuse the code, how to be more conducive to extension, how to be more able to change with the same. Just like the API1 provided by the Microsoft framework, it prevents developers from reinventing the wheel to a certain extent. Take LINQ.NET Framework 3.5 and later versions are packaged and used by millions of developers. The same LINQ syntax, it can support LINQ TO OBJECCT, LINQ TO XML, LINQ TO DATABASE. The benefits of reuse, reduced development effort, and reduced learning costs are self-evident. The learning of LINQ is similar to that of SQL, so if you have used SQL statement, you will feel familiar with it.

Simplicity is one of the great benefits of learning LINQ. The syntax is very much like the syntax of the SQL statement. And learn a technology, can be used as a variety of technologies. This is not like the kind of multi-function knife, 1 knife in hand, life without worry. LINQ supports queries for collections, XML, and databases. Writing code is like talking, much is lost, so optimize your code as much as possible. This not only helps reduce errors, but also increases productivity and reduces maintenance costs. The use of LINQ is also moving in this direction.

To be honest, I've seen a lot of tutorials on LINQ on the Internet, and they're very informative. I could only have the audacity to gallop on the shoulders of giants. This article is basically the source of blog friends in 2008, I feel he wrote very well. Although plagiarism is very shameful behavior, but recall the university can successfully graduate, the paper is also copied 1, west 1. So now I am very "egg fixed". I want to respond to Lord lu's spirit of taking the initiative.

LINQ is a query language, so the scenario used is of course a query. Check which ones, including LINQ TO OBJECCT, LINQ TO XML, LINQ TO DATABASE. It can be said that the range of queries is very wide. For each of them, you can write a series of 1 articles. We will focus on LINQ TO OBJECCT.

Let's look at how we can query the required values from the collection.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace LinqApplication
{
    class People
    {
        /// <summary>
        ///  The name 
        /// </summary>
        public string FirstName { get; set; }
        /// <summary>
        ///  surnames 
        /// </summary>
        public string LastName { get; set; }
        /// <summary>
        ///  countries 
        /// </summary>
        public string Country { get; set; }
    }
    class Program
    {
        static void Main(string[] args)
        {
            List<People> listPeople = new List<People>()
            {
                new People{FirstName="Peter",LastName="Zhang",Country="China"},
                new People{FirstName="Alan",LastName="Guo",Country="Japan"},
                new People{FirstName="Linda",LastName="Tang",Country="China"}
            };
            List<People> result = new List<People>();
            foreach (People p in listPeople)
            {
                if (p.Country == "China")
                {
                    result.Add(p);
                }
            }
            foreach(People p in result)
            {
                Console.WriteLine("Your name is :" + p.FirstName + " " + p.LastName);
            }
            Console.ReadKey();
        }
    }
}

The above method can be said to be the most direct, the easiest way to think of. The above implementation doesn't seem very reusable by any means, but what is the reality? Some of them are good at summing up the above problem, which is to judge whether it is true or not, so they thought of putting it forward for future reuse. Of course, the road to reuse is not a rush, but also accumulated over time. So let's look at the transition as well.


/// <summary>
        ///  To determine if there is 
         /// </summary>
        /// <param name="p"> object </param>
        public static bool IsExist(People p)
        {
            return p.Country == "China";
        }

It would be a waste of effort to implement it in the following way.


foreach (People p in listPeople)
            {
                if (IsExist(p))
                {
                    result.Add(p);
                }
            }

But when combined with the delegate, we can pass IsExist(People p) as a parameter. Here we're going to go a little bit faster, and we're going to take that one piece of code from the query and refer it to another class, Helper, for later use. Let's look at the code implementation of the Helper class. Limited to the length of the problem, only cut Helper class method.


public class Helper
    {
        // Commissioned by the statement 
        public delegate bool ExistPeople(People p);

        /// <summary>
        ///  Get the data that meets the criteria 
         /// </summary>
        /// <param name="listPeople"> The data set </param>
        /// <param name="existPeople"> conditions </param>
        public static List<People> GetPeopleResult(IList<People> listPeople, ExistPeople existPeople)
        {
            List<People> result = new List<People>();
            foreach (People p in listPeople)
            {
                if (existPeople(p))
                {
                    result.Add(p);
                }
            }
            return result;
        }
    }

So we can call it directly to get the data that meets our criteria. You can also use the anonymous delegate provided by C#2.0 or the Lambda representation of C#3.0. The code is as follows:


static void Main(string[] args)
        {
            List<People> listPeople = new List<People>()
            {
                new People{FirstName="Peter",LastName="Zhang",Country="China"},
                new People{FirstName="Alan",LastName="Guo",Country="Japan"},
                new People{FirstName="Linda",LastName="Tang",Country="China"}
            };
            IList<People> result = new List<People>();
 
            // Direct call 
              result = Helper.GetPeopleResult(listPeople, IsExist);
            // Anonymous delegate 
              //result = Helper.GetPeopleResult(listPeople, delegate(People p){ return p.Country == "China" ? true : false;});
            //Lambda expression 
              //result = Helper.GetPeopleResult(listPeople, people => people.Country == "China");           
 
            foreach(People p in result)
            {
                Console.WriteLine("Your name is :" + p.FirstName + " " + p.LastName);
            }
            Console.ReadKey();
        }

At this point, the query for the specific set is basically complete, but C#3.0 also provides a way to make the code more intuitive, which is to extend the method. By extending the methods of the IList collection, we can invoke and pass the delegate condition through IList.

The extension code of Helper class is as follows:


public static class Helper
    {
        // Commissioned by the statement 
        public delegate bool ExistPeople(People p);

        /// <summary>
        ///  Get the data that meets the criteria 
        /// </summary>
        /// <param name="listPeople"> The data set </param>
        /// <param name="existPeople"> conditions </param>
        public static IList<People> GetPeopleResult(this IList<People> listPeople, ExistPeople existPeople)
        {
            List<People> result = new List<People>();
            foreach (People p in listPeople)
            {
                if (existPeople(p))
                {
                    result.Add(p);
                }
            }
            return result;
        }
    }

Let's see if the call to the Main method is intuitive, like calling a collection method and passing a delegate condition. The Main method is as follows:


static void Main(string[] args)
        {
            List<People> listPeople = new List<People>()
            {
                new People{FirstName="Peter",LastName="Zhang",Country="China"},
                new People{FirstName="Alan",LastName="Guo",Country="Japan"},
                new People{FirstName="Linda",LastName="Tang",Country="China"}
            };
            IList<People> result = new List<People>();
            // Direct call 
              //result = Helper.GetPeopleResult(listPeople, IsExist);
            // Anonymous delegate 
              //result = Helper.GetPeopleResult(listPeople, delegate(People p){ return p.Country == "China";});
            //Lambda expression 
              //result = Helper.GetPeopleResult(listPeople, people => people.Country == "China");
            // Extended method call 
              result = listPeople.GetPeopleResult(people => people.Country == "China");
            foreach(People p in result)
            {
                Console.WriteLine("Your name is :" + p.FirstName + " " + p.LastName);
            }
            Console.ReadKey();
        }

The above is using the GetPeopleResult method name, but if we want, can we implement methods such as Select, Where, OrderBy and so on? That's basically the end of the method. One big problem is that it's still dead and inflexible, because it's impossible to say that every object in a collection (in this case, People) is written repeatedly. There must be a way for it to accept different objects so that we can reuse them. Since IList inherits from IEnumerable, you can extend the method to IEnumerable, and then make use of the features of generics to reuse different objects. The code is as follows:


public static class Helper
    {
        public delegate bool Condtion<T>(T t);
        public static IEnumerable<T> GetPeopleResult<T>(this  IEnumerable<T> items, Condtion<T> condition)
        {
            foreach (T t in items)
            {
                if (condition(t))
                {
                    //C# 2.0 In the 1 Key, return 1 An iterator 
                    yield return t;
                }
            }
        }
    }

The Main method does not paste the whole thing, after all, it is repeated several times, only calls the 1 sentence:


IEnumerable<People> result = Helper.GetPeopleResult<People>(listPeople, people => people.Country == "China");

C# 3.0 gives us the var keyword, known as the inferred type.
The var keyword instructs the compiler to infer the type of a variable based on the expression to the right of the initialization statement. Inferred types can be built-in types, anonymous types, user-defined types, types defined in the.NET Framework class library, or any expression. So the formula above can be written as follows:


var result = Helper.GetPeopleResult<People>(listPeople, people => people.Country == "China");

The official end


Related articles: