我想做这样的事情
foreach (var item in SeasonList)
{
if (item.Text == "ALL")
{
item.IsSelected = true;
}
}
我想做这样的事情
foreach (var item in SeasonList)
{
if (item.Text == "ALL")
{
item.IsSelected = true;
}
}
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 是用于查询 - 不是用于更新。