1. Select usage
The select in Linq allows us to easily operate on each item in the List and generate a new list.
var tt=list.select(p=>p+10);
//select括号内为List中的每一项,p+10即为对每一项的操作,即对每项都加10生成新的List
Usage examples:
1. Lambda expression
int[] array = { 1,5,6,7,6,9,12,2,7,6,33};
List<int> l1 = new List<int>(array);
var t1 = l1.Select((p)=>p+10);
foreach (var item in t1)
{
Console.WriteLine(item);
}
The output is:
2. Linq syntax
List<Student_1> stuList = new List<Student_1>()
{
new Student_1(){ID=1,Name="John",Chinese=92,Math=88,English=92},
new Student_1(){ID=2,Name="Mary",Chinese=87,Math=94,English=82},
new Student_1(){ID=3,Name="KangKang",Chinese=89,Math=91,English=96},
new Student_1(){ID=4,Name="Maria",Chinese=88,Math=65,English=94},
new Student_1(){ID=5,Name="Ben",Chinese=70,Math=91,English=82},
};
var t1 = from e in stuList select e.English;
foreach (var item in t1)
{
Console.WriteLine(item);
}
2. SelectMany usage
In C# Linq, the SelectMany method is used to convert each element in a collection to another collection and merge all converted collections into one collection.
List<List<int>> list = new List<List<int>>()
{
new List<int>() { 1, 2, 3 },
new List<int>() { 4, 5, 6 },
new List<int>() { 7, 8, 9 }
};
var result = list.SelectMany(x => x);
foreach (var item in result)
{
Console.WriteLine(item);
}
3. Where usage
where in Linq mainly filters data and generates a new List.
List<Student_1> stuList = new List<Student_1>()
{
new Student_1(){ID=1,Name="John",Chinese=92,Math=88,English=92},
new Student_1(){ID=2,Name="Mary",Chinese=87,Math=94,English=82},
new Student_1(){ID=3,Name="KangKang",Chinese=89,Math=91,English=96},
new Student_1(){ID=4,Name="Maria",Chinese=88,Math=65,English=94},
new Student_1(){ID=5,Name="Ben",Chinese=70,Math=91,English=82},
};
//lambda表达式 表达式内部填的是判断条件
var t1 = stuList.Where(p => p.English == 88);
// Linq 语句
var t1 = from e in stuList where e.English == 82 select e;
It should be noted that the Lambda expression does not need to end with select, but the Linq statement must end with select or an error will be reported.
The running result is:
references: