C#怎么用一行代码把一个集合的属性值根据条件改了,而其他值不变

刚无聊看到群里一位朋友在提问,大晚上没人解答,遂自己默默打开了VS,敲起了代码。

问题:请问怎么将集合newFoods中Name含有"包子"的Number+1,可以一句话写出来 ?

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 }
};

方法有很多种,但是每种的效率是不一样的

其中select会把数据源投射到新表中,所以会慢点

1楼给出的代码更加简洁快速

最后的代码:

 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             //lambda写法1
18             newFoods.ForEach(o =>
19             {
20                 o.Number = o.Name.Contains("包子") ? o.Number + 1 : o.Number;
21             });
22             //lambda写法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

 

posted @ 2015-08-19 01:35  什么都看不懂  阅读(1996)  评论(2编辑  收藏  举报