如果集合中的items bool属性与其他列表中包含的索引匹配/不匹配,请使用LINQ更改它们

本文关键字:请使用 不匹配 LINQ 索引 属性 bool items 集合 其他 如果 包含 | 更新日期: 2023-09-27 18:13:35

我有一个ModelIEnumerable Collection,它包含大约70个项目。

Model myModel = new Model()
{
    Index = 1,
    IsSelected = false
}

我有另一个List<int> Indexes,它可以包含与第一个Collection中的Model的索引中的任何一个匹配的整数。CCD_ 7也可以是空的,但不能是CCD_。

List<int> Indexes = new List<int>() { 3, 21, 33, ...}; 

我设法使用将任何匹配索引的IsSelected属性更改为true

collection.Where(col => Indexes.Any(index => col.Index == index))
.ToList()
.ForEach(a => { a.IsSelected = true; });

但是,对于索引不在List<int> Indexes中的项,如何使用LINQ将IsSelected设置为false?

如果可能的话,我想将那些设置为true和设置为false的LINQ语句组合在一行中。

如果集合中的items bool属性与其他列表中包含的索引匹配/不匹配,请使用LINQ更改它们

collection.Where(m => !Indexes.Contains(m.Index)).ForEach(m => { m.IsSelected = false; });

如果您想在一个语句中设置它们。

collection.ForEach(m => { m.IsSelected = Indexes.Contains(m.Index); });

试试这个

collection.ToList().ForEach(col => { 
      col.IsSelected = Indexes.Contains(col.Index); 
});

相关文章: