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
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
my code gives error can you please tell how i do this
cleaner way to do this is using foreach
foreach(var item in li.Where(w => w.name =="di"))
{
item.age=10;
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With