6

我想做这样的事情

foreach (var item in SeasonList)
{
    if (item.Text == "ALL")
    {
        item.IsSelected = true;
    }
}
4

5 回答 5

24
foreach(var item in SeasonList.Where(x => x.Text == "ALL"))
{
    item.Selected = false;
}
于 2013-02-06T13:20:29.910 回答
9

这也可能有效,但在我看来,你所做的已经很好了。

SeasonList.ForEach(s => s.IsSelected = s.TEXT != "ALL");

或者,要完全匹配初始要求:

SeasonList.Where(s => s.TEXT == "ALL").ToList().ForEach(s => s.IsSelected = false);
于 2013-02-06T13:16:41.250 回答
4
class Program
{
    static void Main(string[] args)
    {
        List<ItemObject> items = new List<ItemObject>()
        {
            new ItemObject() { Text = "Text 1", IsSelected = true },
            new ItemObject() { Text = "Text 2", IsSelected = true },
            new ItemObject() { Text = "ALL", IsSelected = true }
        };

        items.ForEach(x => { if (x.Text == "ALL") x.IsSelected = false; });
    }
}

class ItemObject
{
    public string Text { get; set; }
    public bool IsSelected { get; set; }
}
于 2013-02-06T13:20:34.140 回答
4
SeasonList.ForEach(q => q.IsSelected = q.Text == "ALL" ? false : q.IsSelected)
于 2013-02-06T13:21:34.933 回答
1

使用索引更新

        var index = SeasonList.FindIndex(x => x.Text == "ALL");
        if (index > 0) SeasonList[index].IsSelected = false;

另外一个选项

      foreach (var item in SeasonList.FindAll(x => x.Text == "ALL"))
        {
            item.IsSelected = false;
        }

笔记:

检查 Jon Skeet 的回答LINQ 是用于查询 - 不是用于更新。

于 2013-02-06T13:42:51.797 回答