Linq is easy to use

Posted by beanman1 on Mon, 24 Jun 2019 21:24:11 +0200

  • Query object (list variable in the example above) is IEnumerable < T > or IQueryable < T > type
  • Query returns are also IEnumerable < T > or IQueryable < T > types

Linq is divided into five categories: Linq to objects, Linq to DataSets, Linq to SQL, Linq to Entities, Linq to XML.

Simple use

Type Query Variables= 
               from temporary variable in collection object or database object
               [where conditional expression]
               [order by condition]
               select Temporary Variables or Queried Values in Temporary Variables
               [group by]

(1) General inquiry:

// data source
int[] arr = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

// Linq Query
var result = 
    from item in arr    // Declare the temporary variable item and specify that it is an element in the array arr, item
    where item > 4
    select item;        // Add the query result (item) to result

// Traveling through Linq query results is actually a "Linq query" that is executed with foreach, that is, "Linq query" will not be executed before foreach executes.
foreach(int i in result)
{
    Console.Write(i);   //Output 56789
}

(2) Query and sort:

int[] arr = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

var result = 
    from item in arr
    where item > 4
    orderby item descending // Descending arrangement
    select item;

foreach(int i in result) {
    Console.Write(i);       // Output: 98765
}

(3) Type conversion:

int[] arr = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

var result =
    from item in arr
    where item > 4
    select string.Format("Value:{0} ", item);   // Convert to String type and format it

foreach(string i in result) {   // Change variable i to string type
    Console.Write(i);           // Output "Value: 5 Value: 6 Value: 7 Value: 8 Value: 8 Value"
}

(4) Query for a single value:

int[] arr = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

int result0 = (from item in arr where item > 4 select item).Count();   // The whole sentence is hugged by a pile of () and counted.
int result1 = (from item in arr where item > 4 select item).Max();   // Query maximum

Console.WriteLine(result0); //Output: 5
Console.WriteLine(result1); //Output: 9

from subquery

class Program
{
    static void Main(string[] args)
    {
        // Create a generic variable arr similar to a two-dimensional array to store student information
        List arr = new List 
            { 
                new Student {name = "Lining", scores = new List{11, 12, 34} },
                new Student {name = "ADI", scores = new List{11, 16, 34} },
                new Student {name = "Nike", scores = new List{18, 12} },
            };

        // Query the records of students with scores greater than 15
        var result =
                from stu in arr             // Declare temporary variable stu
                    from sc in stu.scores   // Declare that the temporary variable sc is used for "sub-queries".
                where sc > 15
                select new {name = stu.name, score = sc};    // The query results are "projected" into a new object with two attributes, name and score.

        foreach (var s in result) {
            Console.WriteLine(s.name + ": " + s.score);
        }
    }
}
class Student
{
    public string name;         // Name of student
    public List scores;    // A student's score. A student can have more than one score.
}

Output results:

Li Ning: 34
 Adi: 16
 Adi: 34
 Nike: 18

In the above example, each student has been associated with his score several times, and the query results are stored in a new object (new {...}).

Associating multiple data sources

// Define data sources
char[] upper = { 'A', 'B', 'C' };
char[] lower = { 'x', 'y', 'z' };

// Associate two data sources
var result0 = 
    from up in upper
    from lo in lower
    select new {upper = up, lower=lo};

foreach (var item in result0) {
    Console.WriteLine(item.upper + " " + item.lower);
}

// Associate two data sources and filter by condition
var result1 =
    from up in upper
    from lo in lower
    where up != 'B'
    select new { upper = up, lower = lo };

foreach (var item in result1) {
    Console.WriteLine(item.upper + " " + item.lower);
}

The two output results are as follows:

Grouping

(1) Simple grouping

class Program
{

    static void Main(string[] args)
    {
        // Define data sources
        List<Product> arr = new List<Product>
            {
                new Product{name = "shirt", price = 13.9m, cid = 1},
                new Product{name = "shorts", price = 199.2m, cid = 1},
                new Product{name = "Audi", price = 1.6m, cid = 2},
                new Product{name = "Benz", price = 2.7m, cid = 2},
                new Product{name = "The J-10", price = 82.3m, cid = 3},
                new Product{name = "Broadcasting", price = 91.3m, cid = 3},
            };

        var result = 
            from p in arr
            group p by p.cid;

        // Traversal Groups
        foreach (var gp in result) {
            Console.WriteLine("==============");
            // Traveling through each group member
            foreach (var pd in gp) {
                Console.WriteLine("{0}-{1}-{2}", pd.name, pd.price, pd.cid);
            }
        }

        Console.Read();
    }
}
class Product
{
    public string name;     // Name of commodity
    public decimal price;   // commodity price
    public int cid;         // Classification of commodities
}

Grouping here is not grouping in SQL. Grouping in SQL is mainly used for grouping statistics. The grouping here is to group the original "one-dimensional data" into "two-dimensional data" according to certain rules, and the output results are as follows:

(2) Group Object Processing

    static void Main(string[] args)
    {
        // Define data sources
        List arr = new List
            {
                new Product{name = "shirt", price = 13.9m, cid = 1},
                new Product{name = "shorts", price = 199.2m, cid = 1},
                new Product{name = "Audi", price = 1.6m, cid = 2},
                new Product{name = "Benz", price = 2.7m, cid = 2},
                new Product{name = "The J-10", price = 82.3m, cid = 3},
                new Product{name = "Broadcasting", price = 91.3m, cid = 3},
            };
        List classList = new List
            {
                new Pclass{cname="clothes", cid = 1},
                new Pclass{cname="automobile", cid = 2},
                new Pclass{cname="aircraft", cid = 3},
            };

        var result = 
            from p in arr
            // G is actually a group in the format < Vey, Values >
            // Key is cid for the group
            // Values is the set of elements
            group p by p.cid into G

            from cls in classList 
            where G.Key == cls.cid  // Association Group G and classList Collection
            select new {cname = cls.cname, cid = cls.cid, gplist = G};

        foreach (var gp in result)
        {
            Console.WriteLine();
            Console.WriteLine("Group name:{0},classification id: ", gp.cname, gp.cid);
            foreach (var pd in gp.gplist)
            {
                Console.WriteLine("{0}-{1}-{2}", pd.name, pd.price, pd.cid);
            }
        }
    }
}
class Pclass
{
    public int cid;         // Classification id
    public string cname;    // Category name
}
class Product
{
    public string name;     // Name of commodity
    public decimal price;   // commodity price
    public int cid;         // Classification of commodities
}

The key to the above code lies in the understanding of "into G". The execution process of the query part is as follows:
The first step is to perform grouping, divide a group (cid=1 group) and store it in the temporary variable G; the second step is to associate the grouping G with the set of classList s and store the qualified results in the format specified by select. After the first group is processed, the second group is processed according to the above steps (cid=2), and so on.

Output of program execution:

(3) Delete grouped objects

static void Main(string[] args)
{
    List sts = new List
        {
            new Student{id= 1, name="Lining", cid = 1},
            new Student{id= 2, name="Li Na", cid = 2},
            new Student{id= 3, name="Nike", cid = 3},
            new Student{id= 4, name="ADI", cid = 2},
            new Student{id= 5, name="Benz", cid = 1},
            new Student{id= 6, name="sign up", cid = 3},
        };    

    var result =
        from s in sts
        group s by s.cid into G
        select new { 
            id = G.Key, 
            list = (
                // Excluding students whose id is even
                from m in G
                where (m.id % 2 != 0)
                select m
            )
        };

    foreach (var item in result) {
        Console.WriteLine("Cid: {0}", item.id);
        foreach (var s in item.list) {
            Console.WriteLine("{0}-{1}-{2}", s.id, s.name, s.cid);
        }
    }
}

let clause

Used to create a new temporary variable in a query

static void Main(string[] args)
{
    // Define data sources
    List sts = new List
        {
            new Student{id= 1, name="Lining", cid = 1},
            new Student{id= 2, name="Li Na", cid = 2},
            new Student{id= 3, name="Nike", cid = 3},
            new Student{id= 4, name="ADI", cid = 2},
            new Student{id= 5, name="Benz", cid = 1},
            new Student{id= 6, name="sign up", cid = 3},
        };

    var result =
        from s in sts
        let fullname = s.id + s.name
        select string.Format("id: {0},Full name:{1}", s.id, fullname);

    foreach (string i in result) {
        Console.WriteLine(i);
    }
}

Reprinted at: https://www.cnblogs.com/rainman/archive/2013/06/01/3111752.html

Topics: SQL xml Database