I have a list which I want to update using LINQ.
class Student
{
private string name;
private int marks;
public string Name { get; set;}
public int Marks { get; set; }
public Student(string name, int marks)
{
Name = name;
Marks = marks;
}
}
List<Student> myList = new List<Student>();
myList.Add(new Student("John", 10));
myList.Add(new Student("Tom", 20));
Now I want to update the list using LINQ such that only marks of John gets updated. I am using the following syntax:
myList.Where(w => w.Name == "Tom").Select(w=> { w.Marks = 35; return w});
But this doesnt update data in myList. Can someone tell me where am I going wrong.
Show activity on this post. I have a list which I want to update using LINQ. class Student { private string name; private int marks; public string Name { get; set;} public int Marks { get; set; } public Student(string name, int marks) { Name = name; Marks = marks; } } List<Student> myList = new List<Student>(); myList.
LINQ (Language Integrated Query) is uniform query syntax in C# and VB.NET to retrieve data from different sources and formats. It is integrated in C# or VB, thereby eliminating the mismatch between programming languages and databases, as well as providing a single querying interface for different types of data sources.
Try:
myList .Where(w=> w.Name == "dTomi").ToList().ForEach(i => i.Marks = 35);
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.
As others have pointed out, LINQ is for querying data, it is not for doing updates.
You should iterate your list, and modify your values like:
foreach (var student in myList)
{
if (student.Name == "Tom")
{
student.Marks = 35;
}
}
Or
foreach (var student in myList.Where(r => r.Name == "Tom"))
{
student.Marks = 35;
}
Whatever you think better conveys the intent use that.
but here is an interesting thing:
If you have a statement like:
myList.Where(w => w.Name == "Tom").Select(w => w.Marks = 35).ToList();
Without assigning the result back to myList
the above query will modify the value in the original list. Remember, it is a side effect and it is not the proper way to update. This is modification can be explained by reference parameter being passed to a method and getting modified there. But Importantly, this should always be avoided. It is a bad practice and could lead to really confusing code. Use LINQ for querying only.
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