31

I had a list

List<Myclass> li = new List<Myclass>();

where Myclass is

class Myclass
{
public string name {get;set;}
public decimal age {get;set;}
}

items in li looks like

enter image description here

 i want to update `li` according to name but with `LINQ` like

li.where(w=> w.name = "di") = li.Where(w => w.name =="di").select(s => {s.age = 10;return s;}).Tolist();
li.where(w=> w.name = "marks") = li.Where(w => w.name =="marks").select(s => {s.age = 20;return s;}).Tolist();
li.where(w=> w.name = "grade") = li.Where(w => w.name =="grade").select(s => {s.age = 10;return s;}).Tolist();

and want result which looks like this

enter image description here

my code gives error can you please tell how i do this

4

7 回答 7

97

更干净的方法是使用 foreach

foreach(var item in li.Where(w => w.name =="di"))
{
   item.age=10;
}
于 2013-11-12T13:31:14.973 回答
42

你需要:

li.Where(w=> w.name == "di").ToList().ForEach(i => i.age = 10);

程序代码:

namespace Test
{
    class Program
    {
        class Myclass
        {
            public string name { get; set; }
            public decimal age { get; set; }
        }

        static void Main(string[] args)
        {
            var list = new List<Myclass> { new Myclass{name = "di", age = 0}, new Myclass{name = "marks", age = 0}, new Myclass{name = "grade", age = 0}};
            list.Where(w=> w.name == "di").ToList().ForEach(i => i.age = 10);
            list.ForEach(i => Console.WriteLine(i.name + ":" + i.age));
        }
    }
}

输出:

 di:10
 marks:0
 grade:0
于 2013-11-12T13:33:17.627 回答
10
        li.Where(w => w.name == "di" )
          .Select(s => { s.age = 10; return s; })
          .ToList();
于 2014-08-14T11:13:55.957 回答
5

尝试这个:

li.ForEach(x => x.age = (x.name == "di") ?
                10 : (x.name == "marks") ?
                20 : (x.name == "grade") ?
                30 : 0 );

所有值都在一行代码中更新,您只需浏览一次列表。您还可以设置默认值。

于 2017-07-18T11:13:05.350 回答
4

如果你真的想使用 linq,你可以这样做

li= (from tl in li
    select new Myclass
    {
        name = tl.name,
        age = (tl.name == "di" ? 10 : (tl.name == "marks" ? 20 : 30))

    }).ToList();

或者

li = li.Select(ex => new MyClass { name = ex.name, age = (ex.name == "di" ? 10 : (ex.name == "marks" ? 20 : 30)) }).ToList();

这假设只有 3 种类型的name. 我会将该部分外部化为一个函数,以使其更易于管理。

于 2013-11-12T13:40:30.457 回答
3

尝试Parallel以获得更长的列表:

Parallel.ForEach(li.Where(f => f.name == "di"), l => l.age = 10);
于 2016-09-17T07:09:49.623 回答
1

怎么样

(from k in myList
 where k.id > 35
 select k).ToList().ForEach(k => k.Name = "Banana");
于 2015-09-13T11:08:25.620 回答