0

我有两个列表
列表 A

List<test> populate = new List<test>();
{
  populate.Add(new test(){ID = 1, name="AAA", nameID=1, type=1, isSelected=false});
  populate.Add(new test(){ID = 2, name="BBB", nameID=2, type=1, isSelected=false});
  populate.Add(new test(){ID = 3, name="CCC", nameID=3, type=1, isSelected=false});
}

清单 B

    List<build> populateBuild = new List<build>();
{
  populateBuild.Add(new test(){ID = 1, name="AAA", nameID=1, type=1, isSelected=false});
  populateBuild.Add(new test(){ID = 3, name="CCC", nameID=3, type=1, isSelected=false});
}

我想要实现的是:
1)我想要新列表,(List C)

2)在List C中,我想要 List A 中的所有数据但是 List A 中 isSelected 的将更改为TRUE 当它是与List B中的数据相比 3) 表示,如果List B 存在于 List A 中,则 List A中的 isSelected的值将更改为 TRUE并添加到List C 4) 如果 List B不存在于 List A 中,它仍然会被添加到列表 C,但不更改 isSelected 值(保持为假)。




谢谢,

4

2 回答 2

1

我假设你的意思是List<test> populateBuild = new List<test>();(不是List<build>)。您可以使用生成第三个列表

// Get the ID's of the 2nd list
IEnumerable<int> populateBuildIds = populateBuild.Select(x => x.ID);
// Initialize the 3rd list
List<test> listC = new List<test>();
// Copy all elements from the first list and update the isSelected property
foreach (test t in populate)
{
    listC.Add(new test()
    {
        ID = t.ID, 
        name = t.name, 
        nameID = t.nameID, 
        type = t.type, 
        isSelected = populateBuildIds.Contains(t.ID) // true if also in 2nd list
    });
}
于 2016-07-14T02:43:21.253 回答
0

Adiciona esta classe no seu 项目:

   public static class LINQToObjectExtensions
    {
        public static void UpdateAll<T>(this IEnumerable<T> source, Action<T> action)
        {
            foreach (var item in source)
                action(item);
        }
    }

depois executa desta maneira:

ListC.UpdateAll(p => p.isSelected = ListB.Contains(p));
于 2016-07-14T20:34:39.347 回答