更新列表<;T>;使用foreach循环和使用LINQ/LAMBDA的Condition

本文关键字:LINQ LAMBDA Condition foreach lt 列表 gt 更新 使用 循环 | 更新日期: 2023-09-27 17:57:51

我想做一些类似的事情

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

更新列表<;T>;使用foreach循环和使用LINQ/LAMBDA的Condition

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

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

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

或者,为了完全符合最初的要求:

SeasonList.Where(s => s.TEXT == "ALL").ToList().ForEach(s => s.IsSelected = false);
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; }
}
SeasonList.ForEach(q => q.IsSelected = q.Text == "ALL" ? false : q.IsSelected)

使用索引更新

        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是用于查询,而不是用于更新。