刚无聊看到群里一位朋友在提问,大晚上没人解答,遂自己默默打开了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写法118 newFoods.ForEach(o =>19 {20 o.Number = o.Name.Contains("包子") ? o.Number + 1 : o.Number;21 });22 //Linq写法223 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
新闻热点
疑难解答