LINQ Simple to use

Source: Internet
Author: User

    • Simple to use
    • From sub-query
    • Associating multiple data sources
    • Group
    • Let clause
    • The Query object (the list variable in the example above) is a ienumerable<t> or iqueryable<t> type
    • Query return result is also ienumerable<t> or iqueryable<t> type

LINQ is divided into five categories: LINQ to Objects, LINQ to DataSets, LINQ to SQL, LINQ to Entities, and LINQ to XML.

Simple to use
Type query variable = from                temporary variable in collection object or database object               [where Condition expression]               [order by condition]               the value queried in the Select temporary variable or temporary variable               [GROUP by]

① General Enquiry:

Data source int[] arr = new int[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};//LINQ query var result = from     item in ARR    //Declaration TEMP variable Item, and describes its array of elements in Arr, item    where item > 4    Select item;        Add the query result (item) to result//iterate over the result of the LINQ query, which is actually a LINQ query that is executed with foreach, that is, the LINQ query does not execute a foreach (int i in result) before the foreach execution {    Console.Write (i);   Output 56789}

② 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    Item Descending//descending order    Select Item;foreach (int i in result) {    console.write (i);       Output: 98765}

③ Type conversions:

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 foreach (string i in result) {   //variable i to String type    console.write (i);           Output value: 5 Value: 6 Value: 7 Value: 8 Value: 8 "}

④ Query 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 entire statement is picked up by a bunch of () statistics int result1 = (from item in arr where item > 4 Select Item). Max ();   Query maximum value Console.WriteLine (RESULT0); Output: 5console.writeline (RESULT1); Output: 9
From sub-query
Class program{    static void Main (string[] args)    {        //create a generic variable like a two-dimensional array arr, used to store student information        list arr = new List             {                 new Student {name = "Li ning", scores = new list{11, new                Student {name = "Artie", scores = new list{11, Student}},                new {name = "Nike", scores = new list{18, +},            };        Query for a record with a student score greater than 15        var result = from                stu in arr             //Declaration TEMP variable stu from                    sc in stu.scores   //Declaration TEMP Variable SC for " Subquery ",                where SC >                select new {name = Stu.name, score = SC};    "Project" The query result into a new object that has the name and score two properties.        foreach (var s in result) {            Console.WriteLine (s.name + ":" + S.score);}}    } Class student{public    string name;         Student name public    List scores;    Student scores, a student can have multiple scores}

Output Result:

Li Ning: 34 Artie: 16 Artie: 34 Nike: 18

In the above example, it is true that each student has multiple associations with their scores, and the results are stored in a new object (...} In

Associating multiple data sources
Define data source char[] Upper = {' A ', ' B ', ' C '};char[] lower = {' x ', ' y ', ' z '};//associated 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 criteria var RESULT1 = from the    upper from the    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 were:

Group

① Simple Grouping

Class program{static void Main (string[] args) {//define data source list<product> arr = new List<produc t> {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{nam E = "Mercedes", Price = 2.7m, cid = 2}, New product{name = "J Ten", Price = 82.3m, cid = 3}, new Prod        Uct{name = "broadcast", Price = 91.3m, cid = 3},};        var result = from P in ARR group p by P.cid;            Traverse Group foreach (var gp in result) {Console.WriteLine ("==============");            Traverse each group of members foreach (Var pd in GP) {Console.WriteLine ("{0}-{1}-{2}", Pd.name, Pd.price, pd.cid);    }} console.read ();     }}class product{public string name;   Commodity name: decimal price; Commodity price public intCid Product Category}

The groupings here are not groupings in SQL, and groupings in SQL are used primarily for grouping statistics. And the group here is the original "one-dimensional data" in accordance with a certain rules of the composition of "two-dimensional data", the output of the results:

② Handling of Group objects

    static void Main (string[] args) {//define data source list arr = new List {New Produc T{name = "Shirt", Price = 13.9m, cid = 1}, new product{name = "Shorts", Price = 199.2m, cid = 1}, n                EW product{name = "Audi", Price = 1.6m, cid = 2}, new product{name = "Mercedes", Price = 2.7m, cid = 2},            New Product{name = "J Ten", Price = 82.3m, cid = 3}, new product{name = "broadcast", Price = 91.3m, cid = 3},        }; List classlist = new List {new pclass{cname= "clothes", cid = 1}, new pclass{cname= "car        ", CID = 2}, new Pclass{cname=" Airplane ", cid = 3},};            var result = from P in arr//g is actually a group, formatted as <vey, values> format//key for that group of CID  Values for the set of elements group p by p.cid intoG from CLS in classlist where G.key = = CLS.CID//association group G and classlist collection select new {Cnam        E = cls.cname, cid = cls.cid, gplist = G};            foreach (var gp in result) {Console.WriteLine ();            Console.WriteLine ("group name: {0}, Category 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;    Category ID public string cname;     Category name}class product{public string name;   Commodity name: decimal price;         Commodity price public int CID; Product Category}

The key to the above code is to understand the "into G", the query part of the execution process is:
The first step is to perform the grouping, to separate a group (such as the Cid=1 Group) and save the temporary variable G; then perform the second step, associating the group G with the Classlist collection, storing the eligible results in the select specified format. After the first packet is processed, follow the steps above to process the second grouping (cid=2), and so on.

Program execution output results:

③ to delete a grouped object

static void Main (string[] args) {    list sts = new list        {            new student{id= 1, name= "Li ning", cid = 1},            new Student {id= 2, name= "NA", cid = 2},            new student{id= 3, name= "Nike", cid = 3},            new Student{id= 4, Name= "Artie", CID = 2},            n EW student{id= 5, Name= "Mercedes", CID = 1},            new student{id= 6, name= "Registration", CID = 3},        };        var result = from        s in STS        Group S by s.cid to G        Select new {             id = g.key,             list = (                //Exclude ID Students for even numbers 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 the query

static void Main (string[] args) {    //define Data source    List sts = new list        {            new student{id= 1, name= "Li ning", cid = 1},
   new student{id= 2, name= "Li Na", cid = 2},            new student{id= 3, name= "Nike", cid = 3},            new Student{id= 4, Name= "Artie", CI D = 2},            new student{id= 5, Name= "Mercedes", CID = 1},            new student{id= 6, name= "Registration", 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);    }}

LINQ Simple to use

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.