如何在C#中使用LINQ仅更新对象列表的单个项目

我想更新具有文本属性“ALL”的列表

public class Season { public string Text {get;set;} public string Value {get;set;} public bool ValueSelected {get;set;} } 

LINQ中的“Q”代表“查询”。 LINQ不是要更新对象。

您可以使用LINQ查找要更新的对象,然后“传统”更新它。

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

此代码假定只有一个条目带有Text == "ALL" 。 如果没有或者有多个,此代码将抛出exception。

如果没有或者一个,请使用SingleOrDefault

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

如果有可能存在多个,请使用Where

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

你可以使用这样的东西:

 // Initialize test list. List seasons = new List(); 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 allSeasons = seasons.Where(se => se.Text == "All").ToList(); // Change all values of the selected seasons to "Changed". allSeasons.ForEach(se => se.Value = "Changed");