你的位置:首页 > ASP.net教程

[ASP.net教程]用一句Linq把一个集合的属性值根据条件改了,其他值不变


第一次发博。 - -

刚无聊看到群里一位朋友在提问,大晚上没人解答,遂自己默默打开了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     #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写法18       newFoods = newFoods.Select(o =>19       {20         o.Number = o.Name.Contains("包子") ? o.Number + 1 : o.Number;21         return o;22       }).ToList();23       //普通写法24       for (int i = 0; i < newFoods.Count; i++)25       {26         newFoods[i].Number = newFoods[i].Name.Contains("包子") ? newFoods[i].Number + 1 : newFoods[i].Number;27       }28       //遍历输出29       foreach (Food food in newFoods)30       {31         Console.WriteLine("名称:" + food.Name + ",价格:" + food.Money + ",数量:" + food.Number);32       }33       Console.ReadLine();34     }35     #endregion