大家好,今天是第十天了!
完成三分之一,繼續加油
用 Lambda 找出集合中特定條件下的數量,可使用 Count
語法。
以下範例可找出 Receiver 類別中,name 以 J 開頭的物件數量:
protected class Receiver{
public string name;
public string email;
public Receiver(string n, string m){
name = n;
email = m;
}
}
public void Run(){
List<Receiver> receiver = new List<Receiver>();
receiver.Add(new Receiver("Jack", "Jack@gmail.com"));
receiver.Add(new Receiver("Justin", "Justin@gmail.com"));
receiver.Add(new Receiver("Eddy", "Eddy@hotmail.com"));
receiver.Add(new Receiver("Jeff", "Chen.Jeff@gmail.com"));
int jCount = receiver.Count(n => n.name.StartsWith("J"));
Console.WriteLine("Receiver start with J:" + jCount);
}
結果為:
Receiver start with J:3
若要使用 Lambda 排序,可以使用 OrderBy()
、OrderByDescending()
對欄位分別作遞增、遞減排序。如果需要接著對其它欄位排序,還可以使用 ThenBy()
、ThenByDescending()
。
延續上方的例子,修改內部的 Run 方法,要求以 Receiver 類別的 email 欄位遞增、遞減排序:
public void Run(){
List<Receiver> receiver = new List<Receiver>();
receiver.Add(new Receiver("Jack", "Jack@gmail.com"));
receiver.Add(new Receiver("Justin", "Justin@gmail.com"));
receiver.Add(new Receiver("Eddy", "Eddy@hotmail.com"));
receiver.Add(new Receiver("Jeff", "Chen.Jeff@gmail.com"));
IOrderedEnumerable<Receiver> AscReceiver = receiver.OrderBy(n => n.email);
foreach(Receiver r in AscReceiver){
Console.WriteLine(r.email + "(" + r.name + ")");
}
IOrderedEnumerable<Receiver> DescReceiver = receiver.OrderByDescending(n => n.email);
foreach(Receiver r in DescReceiver){
Console.WriteLine(r.email + "(" + r.name + ")");
}
}
輸出結果為:
Chen.Jeff@gmail.com(Jeff)
Eddy@hotmail.com(Eddy)
Jack@gmail.com(Jack)
Justin@gmail.com(Justin)
Justin@gmail.com(Justin)
Jack@gmail.com(Jack)
Eddy@hotmail.com(Eddy)
Chen.Jeff@gmail.com(Jeff)
C# 3.0 極簡風 - Lambda Expression-黑暗執行緒
c# - Multiple Order By with LINQ - Stack Overflow
c# - Get item count of a list<> using Linq - Stack Overflow