一、select用法
Linq中的select可以使我們的對List中的每一項進行操作,生成新的列表。
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);
}
List<Student> stuList = new List<Student>()
{
new Student(){ID=1,Name="John",Chinese=92,Math=88,English=92},
new Student(){ID=2,Name="Mary",Chinese=87,Math=94,English=82},
new Student(){ID=3,Name="KangKang",Chinese=89,Math=91,English=96},
new Student(){ID=4,Name="Maria",Chinese=88,Math=65,English=94},
new Student(){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);
}
二、SelectMany用法
在C# Linq中,SelectMany方法用于將一個集合中的每個元素轉(zhuǎn)換為另一個集合,并將所有轉(zhuǎn)換后的集合合并為一個新集合。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);
}
三、where用法
where在Linq中主要進行對數(shù)據(jù)篩選,并且生成新的ListList<Student> stuList = new List<Student>()
{
new Student(){ID=1,Name="John",Chinese=92,Math=88,English=92},
new Student(){ID=2,Name="Mary",Chinese=87,Math=94,English=82},
new Student(){ID=3,Name="KangKang",Chinese=89,Math=91,English=96},
new Student(){ID=4,Name="Maria",Chinese=88,Math=65,English=94},
new Student(){ID=5,Name="Ben",Chinese=70,Math=91,English=82},
};
var t1 = stuList.Where(p => p.English == 88);
// Linq 語句
var t1 = from e in stuList where e.English == 82 select e;
需要注意的是Lambda表達式中不需要select結(jié)尾,但Linq 語句必須是select結(jié)尾否則報錯四、C# linq 將數(shù)組轉(zhuǎn)換為以逗號分隔的字符串string[] array = { "A", "B", "C", "D" };
string str = string.Join(",", array);
該文章在 2025/1/13 10:44:31 編輯過