SoFunction
Updated on 2025-03-06

Examples of basic operation of Linq query in C#

Abstract: This article introduces the basic operations of Linq query (query keywords)

- from clause

- where clause

- select clause

- group clause

- into clause

- orderby clause

- join clause

- let clause

- Compound from clause

- In some cases, each element in the source sequence may itself be a sequence (set) or may contain a sequence

- Term access to internal collections in a single database

- Use multiple from words to perform connection

- Can contain multiple from words that can generate supplemental queries from independent data sources

Compound (as the name implies, it is the word "from") example:

Copy the codeThe code is as follows:

class Program
{ static void Main(string[] args)
    {
        List<Student> students = new List<Student> { new Student
            {
                LastName="xiaogui",Scores=new List<int>{97,42,91,60}}, new Student
                {
                    LastName="xiaozhan",Scores=new List<int>{50,92,81,60}}, new Student
                    {
                        LastName="xiaolan",Scores=new List<int>{32,32,81,90}}, new Student
                        {
                            LastName="xiaowan",Scores=new List<int>{92,22,81,60}},        
        }; var query = from stuent in students from score in where score > 90 select new {
                        Last = ,
                        score
}; foreach (var student in query)// Show more than 90 points  {
            ("{0} Score:{1}", , );
        }
        ();
    }
}

Copy the codeThe code is as follows:

public class Student
{ public string LastName { get; set; } public List<int> Scores { get; set; }
} public class Employee
{ public string First { get; set; } public string Last { get; set; } public int ID { get; set; }
}

Execution result: xiaogui Score:97

              xiaogui Score:91

              xiaozhan Score:92

              xiaowan Score:92

let keyword (using let word to extend scope variable)

- Create an enumerable type that can query itself

- Make the query call ToLower only once on the scope variable word.

If you do not use let, you must call ToLower in each predicate of the where sentence

Example: Find out which contains a or e at the beginning of each word

Copy the codeThe code is as follows:

using System; using ; public class Test
{ static void Main(string[] args)
    { string[] strings = { "A penny saved is a penny earned.", "The aaxly sdj", "the pa is no" }; var query = from sentence in strings
let words = (' ')//Split into arrays with spaces from word in words
let w = ()//Lowercase for each letter where w[0] == 'a' || w[0] == 'e' select word; foreach (var s in query)
        {
            (s);
        }
        ();
    }
}

where keywords (filter)

- A query expression can contain multiple where sentences

Example: (Find out the one containing a)

Copy the codeThe code is as follows:

using System; using ; public class Test
{ static void Main(string[] args)
    { string[] str = { "a", "b", "c" }; var query = from s in str where s == "a" select s; foreach (var s in query)
        {
            (s);
        }
        ();
    }
}

orderby keywords (sort)

- In a query expression, the orderby sentence can cause the returned sequence (group) to be in ascending or descending order.

- Multiple keys can be specified to perform one or more secondary sorting operations

- The default sorting order is ascending

- When compiled, the orderby sentence is converted into a call to the OrderBy method. Multiple keys in the orderby sentence are converted to ThenBy method calls

descending descending

ascending

Example 1: Ascending order

Copy the codeThe code is as follows:

using System; using ; public class Test
{ static void Main(string[] args)
    { string[] str = { "a", "b", "c" }; var query = from s in str orderby s ascending select s;
    }
}

The result is: a b c

Example 2: descending order

Copy the codeThe code is as follows:

using System; using ; public class Test
{ static void Main(string[] args)
    { string[] str = { "a", "b", "c" }; var query = from s in str orderby s descending select s;
    }
}

The result is: c b a

group keywords (group)

- group sentence returns an IGrouping(TKey,Telement) object sequence

- When compiling, the group clause is converted to a call to the GroupBy method

(LINQ query expressions can end with select or group) (If you want to perform additional query operations on each group, you can specify a temporary identifier using the into context keyword. When using into, you must continue to write the query and end with a select statement or another group clause)

example:

Copy the codeThe code is as follows:

using System; using ; public class Test
{ static void Main(string[] args)
    { string[] str = { "aa", "bb", "cc", "dd" }; var query = from s in str
                    group s by s[0]
                        into p where == 'a' || == 'b' || == 'c' orderby descending select ; foreach (var s in query)
        {
            (s);
        }
        ();
    }
}

The result is: c b a

Description: group s by s[0] into p means grouping with "s[0]" for the range variable s, in this example, grouping with the first letter

join keywords (join)

- Use the join clause to associate elements from different source sequences and have no direct relationships in the object model

- The only requirement is that each source needs to share a value that can be compared to determine whether it is equal

- Join sentence uses special equals keyword to compare whether the specified keys are equal

Common connection types among the three

- Internal connection

- Grouping Join

- Left external join

1. Internal connection

Copy the codeThe code is as follows:

var query = from a in str
join b in str2 on equals select new { Aname = , Bname = };

2. Grouping and joining: (into can temporarily save the join)

Copy the codeThe code is as follows:

var query = from a in str
join b in str2 on equals
into c select new {Aname=,Cs=c}

3. Left external connection

- In the left outer join, all elements in the left source sequence will be returned, even if they have no matching elements in the right sequence.

- To perform a left outer join in LINQ, combine the DefaultifEmpty method with a group join to specify the default right element to be generated when a left element does not have a matching element. Can use null as any quotation

Use the default value of the type, you can also specify the user-defined default type.

Copy the codeThe code is as follows:

var query = from category in categories
join prod in products on equals
into prodGroup from item ( new Product{Name=,CategoryID=0}) select new {CatName=,ProdName=}

equalse operator

- The join clause performs the same join. In other words, matches can only be based on the equality relationship between two keys

- To show that all joins are equal joins, the join clause uses the equals keyword instead of the == operator

Compound keys

- Use compound keys to test whether multiple values ​​are equal

select keyword selection