欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

LInq 学习笔记

程序员文章站 2022-07-03 23:27:23
...

 学习网站http://www.tutorialsteacher.com/linq/linq-joining-operator-join


// Student collection

IList<Student> studentList = new List<Student>>() {

        newStudent() { StudentID = 1, StudentName= "John", Age = 13} ,

        newStudent() { StudentID = 2, StudentName= "Moin" Age = 21 } ,

        newStudent() { StudentID = 3, StudentName= "Bill" Age = 18 } ,

        newStudent() { StudentID = 4, StudentName= "Ram" , Age = 20} ,

        newStudent() { StudentID = 5, StudentName= "Ron" , Age = 15 }

    };

 

// LINQ Query Syntax to find out teenager students

var teenAgerStudent = from s in studentList

                     where s.Age > 12 && s.Age< 20

                     select s;

   var treestudent= studentList.where(s=>s.Age>20);

var teenAgerStudents = studentList.Where(s => s.Age > 12 && s.Age < 20)
                                  .ToList<Student>();

 

s =>
{
   int youngAge = 18;
 
    Console.WriteLine("Lambda expression with multiple statements in the body");
 
    return s.Age >= youngAge;
}
 
 
1 where
 
IList<Student> studentList = newList<Student>() { 
        newStudent() { StudentID = 1, StudentName = "John", Age = 13} ,
        newStudent() { StudentID = 2, StudentName = "Moin"Age = 21 } ,
        newStudent() { StudentID = 3, StudentName = "Bill"Age = 18 } ,
        newStudent() { StudentID = 4, StudentName = "Ram" , Age = 20} ,
        newStudent() { StudentID = 5, StudentName = "Ron" , Age = 15 } 
    };
 
 
var filteredResult = from s in studentList
                    where s.Age > 12 && s.Age < 20
                    select s.StudentName;
 
---------------------------------------------------
 
public static void Main()
{
    var filteredResult = from s in studentList
                         where isTeenAger(s)
                         select s;
}
 
public static bool IsTeenAger(Student stud)
{
    return stud.Age > 12 && stud.Age < 20;  
}
 
--------------------------------------------------------
 
IList<Student> studentList = newList<Student>() { 
        newStudent() { StudentID = 1, StudentName = "John", Age = 18 } ,
        newStudent() { StudentID = 2, StudentName = "Steve"Age = 15 } ,
        newStudent() { StudentID = 3, StudentName = "Bill"Age = 25 } ,
        newStudent() { StudentID = 4, StudentName = "Ram" , Age = 20 } ,
        newStudent() { StudentID = 5, StudentName = "Ron" , Age = 19 } 
    };
 
var filteredResult = studentList.Where((s, i) => { 
            if(i % 2 ==  0) // if it is even element
                returntrue;
                
        returnfalse;
    });
 
foreach (var std in filteredResult)
        Console.WriteLine(std.StudentName);
 
 
----------------------------------------------------------------------------

var filteredResult = from s in studentList

                   where s.Age > 12

                   where s.Age < 20

                   select s;

 

var filteredResult = studentList.Where(s => s.Age > 12).Where(s=> s.Age < 20);

 
OfType
 
IList mixedList = newArrayList();
mixedList.Add(0);
mixedList.Add("One");
mixedList.Add("Two");
mixedList.Add(3);
mixedList.Add(new Student() { StudentID = 1, StudentName = "Bill" });
 
var stringResult = from s in mixedList.OfType<string>()// result: One Two
                   select s;
 
var intResult = from s in mixedList.OfType<int>()//Result 0 3
                select s;
 
 
OrderBy
IList<Student> studentList = newList<Student>() { 
    newStudent() { StudentID = 1, StudentName = "John", Age = 18 } ,
    newStudent() { StudentID = 2, StudentName = "Steve"Age = 15 } ,
    newStudent() { StudentID = 3, StudentName = "Bill"Age = 25 } ,
    newStudent() { StudentID = 4, StudentName = "Ram" , Age = 20 } ,
    newStudent() { StudentID = 5, StudentName = "Ron" , Age = 19 } 
};
 
var orderByResult = from s in studentList
                   orderby s.StudentName 
                   select s;
 
var orderByDescendingResult = from s in studentList
                   orderby s.StudentName descending
                   select s;

IList<Student> studentList = newList<Student>() { 
    newStudent() { StudentID = 1, StudentName = "John", Age = 18 } ,
    newStudent() { StudentID = 2, StudentName = "Steve"Age = 15 } ,
    newStudent() { StudentID = 3, StudentName = "Bill"Age = 25 } ,
    newStudent() { StudentID = 4, StudentName = "Ram" , Age = 20 } ,
    newStudent() { StudentID = 5, StudentName = "Ron" , Age = 19 } 
};
 
var studentsInAscOrder = studentList.OrderBy(s => s.StudentName);
 
 
IList<Student> studentList = newList<Student>() { 
 
    newStudent() { StudentID = 1, StudentName = "John", Age = 18 } ,
    newStudent() { StudentID = 2, StudentName = "Steve"Age = 15 } ,
    newStudent() { StudentID = 3, StudentName = "Bill"Age = 25 } ,
    newStudent() { StudentID = 4, StudentName = "Ram" , Age = 20 } ,
    newStudent() { StudentID = 5, StudentName = "Ron" , Age = 19 } 
};
 
var studentsInDescOrder = studentList.OrderByDescending(s => s.StudentName);
 
 
IList<Student> studentList = newList<Student>() { 
    newStudent() { StudentID = 1, StudentName = "John", Age = 18 } ,
    newStudent() { StudentID = 2, StudentName = "Steve"Age = 15 } ,
    newStudent() { StudentID = 3, StudentName = "Bill"Age = 25 } ,
    newStudent() { StudentID = 4, StudentName = "Ram" , Age = 20 } ,
    newStudent() { StudentID = 5, StudentName = "Ron" , Age = 19 }, 
    newStudent() { StudentID = 6, StudentName = "Ram" , Age = 18 }
};
 
var orderByResult = from s in studentList
                   orderby s.StudentName, s.Age 
                   select new { s.StudentName, s.Age };
 
 
ThenBy  MUti order
 
IList<Student> studentList = newList<Student>() { 
    newStudent() { StudentID = 1, StudentName = "John", Age = 18 } ,
    newStudent() { StudentID = 2, StudentName = "Steve"Age = 15 } ,
    newStudent() { StudentID = 3, StudentName = "Bill"Age = 25 } ,
    newStudent() { StudentID = 4, StudentName = "Ram" , Age = 20 } ,
    newStudent() { StudentID = 5, StudentName = "Ron" , Age = 19 }, 
    newStudent() { StudentID = 6, StudentName = "Ram" , Age = 18 }
};
var thenByResult = studentList.OrderBy(s => s.StudentName).ThenBy(s => s.Age);
 
var thenByDescResult = studentList.OrderBy(s => s.StudentName).ThenByDescending(s => s.Age);
 

GroupBy & ToLookup


IList<Student> studentList = new List<Student>() {

        new Student() { StudentID = 1, StudentName= "John", Age = 18 } ,

        new Student() { StudentID = 2, StudentName= "Steve"Age = 21 } ,

        new Student() { StudentID = 3, StudentName= "Bill"Age = 18 } ,

        new Student() { StudentID = 4, StudentName= "Ram" , Age = 20 } ,

        new Student() { StudentID = 5, StudentName= "Abram" , Age = 21 }

    };

 

var groupedResult = from s in studentList

                   group s by s.Age;

 

//iterate each group       

foreach (var ageGroup in groupedResult)

{

    Console.WriteLine("Age Group: {0}", ageGroup .Key); //Each grouphas a key

            

    foreach(Student s in ageGroup) // Each grouphas inner collection

        Console.WriteLine("Student Name: {0}", s.StudentName);

--------------------------------------------

var groupedResult = studentList.GroupBy(s =>s.Age);

 

ToLookup

ToLookup is the same as GroupBy; the only difference is GroupBy execution is deferred, whereas ToLookup execution is immediate. Also, ToLookup is only applicable in Method syntax. ToLookup is not supported in the query syntax.

Example: ToLookup in method syntax C#

IList<Student> studentList = new List<Student>() { 
        new Student() { StudentID = 1, StudentName = "John", Age = 18 } ,
        new Student() { StudentID = 2, StudentName = "Steve",  Age = 21 } ,
        new Student() { StudentID = 3, StudentName = "Bill",  Age = 18 } ,
        new Student() { StudentID = 4, StudentName = "Ram" , Age = 20 } ,
        new Student() { StudentID = 5, StudentName = "Abram" , Age = 21 } 
    };

var lookupResult = studentList.ToLookup(s => s.age);

foreach (var group in lookupResult)
{
    Console.WriteLine("Age Group: {0}", group.Key);  //Each group has a key 
             
    foreach(Student s in group)  //Each group has a inner collection  
        Console.WriteLine("Student Name: {0}", s.StudentName);
}

 

Join


The result like the opration inner jion in sql

Join in Method Syntax:

Join() method overloads:
public static IEnumerable<TResult> Join<TOuter, TInner, TKey, TResult>(this IEnumerable<TOuter> outer, 
                                                        IEnumerable<TInner> inner, Func<TOuter, TKey> outerKeySelector, 
                                                        Func<TInner, TKey> innerKeySelector, 
                                                        Func<TOuter, TInner, TResult> resultSelector);

public static IEnumerable<TResult> Join<TOuter, TInner, TKey, TResult>(this IEnumerable<TOuter> outer, 
                                                        IEnumerable<TInner> inner, 
                                                        Func<TOuter, TKey> outerKeySelector,
                                                        Func<TInner, TKey> innerKeySelector, 
                                                        Func<TOuter, TInner, TResult> resultSelector,
                                                        IEqualityComparer<TKey> comparer);

As you can see in the first overload method takes five input parameters (except the first 'this' parameter): 1) outer 2) inner 3) outerKeySelector 4) innerKeySelector 5) resultSelector.

Let's take a simple example. The following example joins two string collection and return new collection that includes matching strings in both the collection.

Example: Join operator C#

IList<string> strList1 = new List<string>() { 
    "One", 
    "Two", 
    "Three", 
    "Four"
};

IList<string> strList2 = new List<string>() { 
    "One", 
    "Two", 
    "Five", 
    "Six"
};

var innerJoin = strList1.Join(strList2,
                      str1 => str1, 
                      str2 => str2, 
                      (str1, str2) => str1);


The following example demonstrates LINQ Join query.

Example: Join Query C#

IList<Student> studentList = new List<Student>() { 
    new Student() { StudentID = 1, StudentName = "John", StandardID =1 },
    new Student() { StudentID = 2, StudentName = "Moin", StandardID =1 },
    new Student() { StudentID = 3, StudentName = "Bill", StandardID =2 },
    new Student() { StudentID = 4, StudentName = "Ram" , StandardID =2 },
    new Student() { StudentID = 5, StudentName = "Ron"  } 
};

IList<Standard> standardList = new List<Standard>() { 
    new Standard(){ StandardID = 1, StandardName="Standard 1"},
    new Standard(){ StandardID = 2, StandardName="Standard 2"},
    new Standard(){ StandardID = 3, StandardName="Standard 3"}
};

var innerJoin = studentList.Join(// outer sequence 
                      standardList,  // inner sequence 
                      student => student.StandardID,    // outerKeySelector
                      standard => standard.StandardID,  // innerKeySelector
                      (student, standard) => new  // result selector
                                    {
                                        StudentName = student.StudentName,
                                        StandardName = standard.StandardName
                                    });


The following example of Join operator in query syntax returns a collection of elements from studentList and standardList if their Student.StandardID and Standard.StandardID is match.

Example: Join operator in query syntax C#

IList<Student> studentList = new List<Student>() { 
    new Student() { StudentID = 1, StudentName = "John", Age = 13, StandardID =1 },
    new Student() { StudentID = 2, StudentName = "Moin",  Age = 21, StandardID =1 },
    new Student() { StudentID = 3, StudentName = "Bill",  Age = 18, StandardID =2 },
    new Student() { StudentID = 4, StudentName = "Ram" , Age = 20, StandardID =2 },
    new Student() { StudentID = 5, StudentName = "Ron" , Age = 15 } 
};

IList<Standard> standardList = new List<Standard>() { 
    new Standard(){ StandardID = 1, StandardName="Standard 1"},
    new Standard(){ StandardID = 2, StandardName="Standard 2"},
    new Standard(){ StandardID = 3, StandardName="Standard 3"}
};

var innerJoin = from s in studentList // outer sequence
                      join st in standardList //inner sequence 
                      on s.StandardID equals st.StandardID // key selector 
                      select new { // result selector 
                                    StudentName = s.StudentName, 
                                    StandardName = st.StandardName 
                                };