6

我想更新Value具有属性的列表Text="ALL"

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

2 回答 2

23

LINQ 中的“Q”代表“查询”。LINQ 并不意味着更新对象。

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

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

toUpdate.ValueSelected = true;

此代码假定只有一个带有Text == "ALL". 如果没有或有多个,此代码将引发异常。

如果没有或没有,请使用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;
于 2013-02-06T12:37:56.503 回答
4

你可以使用这样的东西:

// 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"); 
于 2013-02-06T12:45:15.630 回答