2022 鐵人賽文 搬回點部落
開始試煉
在做Linq查詢的時候 常會因為where條件後怕沒有東西了
這時候接著下Max之類的語法 就會炸例外像是這樣
var list = new List<int>() { 1, 2, 3, 4, 5 };
list.Where(x => x > 10).Min().Dump("Min");

所以還要先判斷any…等
其實DefaultIfEmpty就超好用
var list = new List<int>() { 1, 2, 3, 4, 5 };
list.Where(x => x > 10)
.DefaultIfEmpty()
.Min()
.Dump("Min");

也可以改變Default,DefaultIfEmpty(-1) 這樣結果就是-1
字串也一樣
var list = new List<string>() { "a", "b", "c", "d" };
list.Where(x => x.StartsWith("z"))
.DefaultIfEmpty("NO DATA")
.Dump();
list.Where(x => x.StartsWith("z"))
.DefaultIfEmpty("NO DATA")
.First()
.Dump();

自訂物件也可以
void Main()
{
var prodcutList = new List<Prodcut>()
{
new Prodcut{ Name= "Sports & Outdoors", Price= 1200 },
new Prodcut{ Name= "Pet Supplies", Price= 2400 },
new Prodcut{ Name= "Toys & Games", Price= 5600 }
};
prodcutList.Where(x => x.Price > 6000)
.DefaultIfEmpty(new Prodcut())
.Max(x => x.Price)
.Dump("Max Price");
}
public class Prodcut
{
public string Name { get; set; }
public int Price { get; set; }
}

結束試煉
Linq 真是強大
如果內容有誤請多鞭策謝謝