Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

conditional Updating a list using LINQ

Tags:

c#

list

linq

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

like image 512
Amit Bisht Avatar asked Nov 12 '13 13:11

Amit Bisht


2 Answers

cleaner way to do this is using foreach

foreach(var item in li.Where(w => w.name =="di"))
{
   item.age=10;
}
like image 82
Kamil Budziewski Avatar answered Oct 13 '22 08:10

Kamil Budziewski


You need:

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

Program code:

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

Output:

 di:10
 marks:0
 grade:0
like image 30
Baldrick Avatar answered Oct 13 '22 08:10

Baldrick