第一次發博。 - -
剛無聊看到群裡一位朋友在提問,大晚上沒人解答,遂自己默默打開了VS,敲起了代碼。
問題:請問怎麼將集合newFoods中Name含有"包子"的Number+1,LINQ可以一句話寫出來 ?
List<Food> newFoods = new List<Food>{ new Food { Money = 10, Name = "天津包子", Number=1 }, new Food { Money = 10, Name = "狗不理包子", Number = 1 }, new Food { Money = 10, Name = "小籠包子", Number = 1 }, new Food { Money = 10, Name = "饅頭", Number = 1 }, new Food { Money = 10, Name = "粽子", Number = 1 } };
我先是敲了一下正常的寫法,很快出來了。
但是用Linq一直不知道該怎麼寫,反而越寫越麻煩,還想出准備先篩選出一個對象,再把兩個對象合並的傻辦法。
後來發現原來select裡是可以直接查詢完返回原對象的。之前用Linq一直以為只能是 model.Select(o=>o.property==xxx) 這樣用,也沒去深究,看來是修為不夠。
1樓給出的代碼更加簡潔快速,Linq真是方便
最後的代碼:
1 #region 2 public class Food 3 { 4 public string Name { get; set; } 5 public int Money { get; set; } 6 public int Number { get; set; } 7 } 8 static void Example1() 9 { 10 List<Food> newFoods = new List<Food>{ 11 new Food { Money = 10, Name = "天津包子", Number=1 }, 12 new Food { Money = 10, Name = "狗不理包子", Number = 1 }, 13 new Food { Money = 10, Name = "小籠包子", Number = 1 }, 14 new Food { Money = 10, Name = "饅頭", Number = 1 }, 15 new Food { Money = 10, Name = "粽子", Number = 1 } 16 }; 17 //Linq寫法1 18 newFoods.ForEach(o => 19 { 20 o.Number = o.Name.Contains("包子") ? o.Number + 1 : o.Number; 21 }); 22 //Linq寫法2 23 newFoods = newFoods.Select(o => 24 { 25 o.Number = o.Name.Contains("包子") ? o.Number + 1 : o.Number; 26 return o; 27 }).ToList(); 28 //普通寫法 29 for (int i = 0; i < newFoods.Count; i++) 30 { 31 newFoods[i].Number = newFoods[i].Name.Contains("包子") ? newFoods[i].Number + 1 : newFoods[i].Number; 32 } 33 //遍歷輸出 34 foreach (Food food in newFoods) 35 { 36 Console.WriteLine("名稱:" + food.Name + ",價格:" + food.Money + ",數量:" + food.Number); 37 } 38 Console.ReadLine(); 39 } 40 #endregion