How to update only one item list item using LINQ in C #

I want to update a list that has the text property "ALL"

public class Season { public string Text {get;set;} public string Value {get;set;} public bool ValueSelected {get;set;} } 
+4
source share
2 answers

"Q" in LINQ means "Query". LINQ is not intended to update objects.

You can use LINQ to find the object you want to update, and then update it โ€œtraditionallyโ€.

 var toUpdate = _seasons.Single(x => x.Text == "ALL"); toUpdate.ValueSelected = true; 

This code assumes that there is only one entry with Text == "ALL" . This code throws an exception if it does not exist or there are several.

If there is none, none, use SingleOrDefault :

 var toUpdate = _seasons.SingleOrDefault(x => x.Text == "ALL"); if(toUpdate != null) toUpdate.ValueSelected = true; 

If it is possible that there are several, use Where :

 var toUpdate = _seasons.Where(x => x.Text == "ALL"); foreach(var item in toUpdate) item.ValueSelected = true; 
+18
source

You can use something like this:

 // Initialize test list. List<Season> seasons = new List<Season>(); seasons.Add(new Season() { Text = "All" }); seasons.Add(new Season() { Text = "1" }); seasons.Add(new Season() { Text = "2" }); seasons.Add(new Season() { Text = "All" }); // Get all season with Text set to "All". List<Season> allSeasons = seasons.Where(se => se.Text == "All").ToList(); // Change all values of the selected seasons to "Changed". allSeasons.ForEach(se => se.Value = "Changed"); 
+4
source

All Articles