码迷,mamicode.com
首页 > 其他好文 > 详细

用一句Linq把一个集合的属性值根据条件改了,其他值不变

时间:2015-08-19 01:58:49      阅读:101      评论:0      收藏:0      [点我收藏+]

标签:

第一次发博。 - -

刚无聊看到群里一位朋友在提问,大晚上没人解答,遂自己默默打开了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

 

用一句Linq把一个集合的属性值根据条件改了,其他值不变

标签:

原文地址:http://www.cnblogs.com/simendancer/p/4741141.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!