C# 使用 foreach 循环和 Condition 使用 LINQ/LAMBDA 更新 List<T>

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14729973/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 12:50:49  来源:igfitidea点击:

Update List<T> using foreach loop and Condition using LINQ/LAMBDA

c#

提问by Gowtham

I want to do something like this

我想做这样的事情

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

采纳答案by Aron

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

回答by Larry

This may work also, but in my opinion, what you did is already good.

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

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

Or, to match exactly initial requirements :

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

SeasonList.Where(s => s.TEXT == "ALL").ToList().ForEach(s => s.IsSelected = false);

回答by Rick Liddle

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; }
}

回答by daryal

SeasonList.ForEach(q => q.IsSelected = q.Text == "ALL" ? false : q.IsSelected)

回答by C-va

Update using index

使用索引更新

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

Another option

另外一个选项

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

Note:

笔记:

Check Jon Skeet's answer LINQ is for querying - not for updating.

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