I have a list which I want to update using LINQ.
class Student
{
private string name;
private int marks;
public string Name { get; set;}
pub
LINQ is for querying, not for updating the data. Use LINQ to get the items that you want to modify, and then modify them in a foreach loop:
foreach ( var tom in myList.Where(w => w.Name == "Tom")) {
tom.Marks = 35;
}
Demo.
Select(), like any other LINQ method, doesn't change a source collection, instead, it return a new collection.
So you should either assign that new collection to myList:
myList = myList.Where(w => w.Name == "Tom").Select(w => { w.Marks = 35; return w}).ToList();
or assign Marks property in a separate foreach loop
myList.Where(w => w.Name == "Tom").ToList().ForEach(w => w.Marks = 35);
This is kind of clunky, but works, and doesn't depend on being passed a reference. It creates a new list based on the old.
var myList=myList.Select(l=>new Student {
l.Name,
Marks=l.Name=="Tom"?35:l.Marks}).ToList();
Or more silly:
var myList=myList.Where(l=>l.Name!="Tom").Union(
myList.Where(l=>l.Name=="Tom").Select(l=>new Student {
l.Name,
Marks=35})).ToList();
how about old good for loop
for(int i = 0; i < myList.Count; i++)
if (myList[i].Name == "Tom")
{
myList[i].Marks = 35;
break;
}
well @dasblinkenlight code should work but you can also try something like this
var query = from x in list
where x.Name = yourcondition
select new { x };
foreach(var item in query)
item.x.FieldToUpdate = SetValue;
Try:
myList .Where(w=> w.Name == "dTomi").ToList().ForEach(i => i.Marks = 35);