The Linq query base operation in C USES instances

  • 2020-05-30 20:56:38
  • OfStack

Abstract: this article describes the basic operation of Linq query (query keyword).

- from clauses

- where clauses

- select clauses

- group clauses

- into clauses

- orderby clauses

- join clauses

- let clauses

- compound from clause

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

- terms for accessing internal collections in a single database

- connect using multiple from words

- can contain multiple from phrases that can generate supplementary queries from independent data sources

Compound (as the name implies, there are multiple from words) instances:


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 stuent.Scores where score > 90 select new {
                        Last = stuent.LastName,
                        score
                    }; foreach (var student in query)// Is greater than 90 Points are displayed    {
            Console.WriteLine("{0} Score:{1}", student.Last, student.score);
        }
        Console.ReadLine();
    }
}


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

Results: xiaogui Score:97

xiaogui Score:91

xiaozhan Score:92

xiaowan Score:92

let keyword (use let to extend range variable)

- create an enumerable type that can query itself

- allows the query to call ToLower only once on the range variable word.

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

Example: find out if the beginning of each word contains a or e


using System; using System.Linq; 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 = sentence.Split(' ')// Split an array with Spaces   from word in words
                    let w = word.ToLower()// Lower case each letter   where w[0] == 'a' || w[0] == 'e' select word; foreach (var s in query)
        {
            Console.WriteLine(s);
        }
        Console.ReadLine();
    }
}

where keyword (filter)

- 1 query expression can contain more than one where phrase

Example :(find out what contains a)


using System; using System.Linq; 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)
        {
            Console.WriteLine(s);
        }
        Console.ReadLine();
    }
}

orderby keyword (sort)

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

- you can specify multiple keys to perform one or more secondary sort operations

- the default sort order is ascending

- at compile time, the orderby sentence is converted to a call to the OrderBy method. Multiple keys in the orderby sentence are converted to ThenBy method calls

descending descending

ascending ascending

Example 1: ascending order


using System; using System.Linq; 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: a b c

Example 2: descending order


using System; using System.Linq; 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 keyword (grouping)

-group returns a sequence of IGrouping(TKey,Telement) objects

- at compile time, 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. With into, you must continue to write the query and end the query with either an select statement or another group clause.)

Ex. :


using System; using System.Linq; 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 p.Key == 'a' || p.Key == 'b' || p.Key == 'c' orderby p.Key descending select p.Key; foreach (var s in query)
        {
            Console.WriteLine(s);
        }
        Console.ReadLine();
    }
}

The result is: c b a

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

join keyword (join)

- use the join clause to associate elements from different source sequences that are not directly related in the object model

The requirement of -only 1 is that each element in the source needs to share some value that can be compared to determine if it is equal

-join compares the specified keys using the special equals keyword

Common connection types in 3

- internal connection

- group join

- left outer join

1. Internal connection


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

2. Group join :(into can temporarily save join)


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

3. Left outer connection

- in the left outer join, all elements in the left source sequence are 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. You can use null for any lead

You can also specify a user-defined default type with the default value of the type.


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

equalse operator.

- join clause performs an equal join. In other words, matches can only be made based on the equality between the two keys

- to indicate that all joins are equally joined, the join clause USES the equals keyword instead of the == operator

Composite key

- multiple values can be tested for equality using a composite key

select keyword selection


Related articles: