从列表A中选择不在列表B中的项目,反之亦然

时间:2016-05-24 18:56:34

标签: c# linq

我有两个AB列表,并试图从A中获取不在BB中的元素A

以下是我尝试解决此问题。

var result = (List<string>)(from e in (A.Concat(B))
where !B.Contains(e) || !A.Contains(e)
select e);

并遇到以下错误..

  

无法投射类型的对象   要输入WhereEnumerableIterator1 [System.String]   System.Collections.Generic.List`1 [System.String]。

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:2)

您可以使用Except

List<int> firstList = new List<int> {1,2,3,4};

List<int> secondList = new List<int> { 1, 5 };

IEnumerable<int> res = secondList.Except(firstList).Concat(firstList.Except(secondList));

//Result => {5,2,3,4}

答案 1 :(得分:1)

关于你的投射错误,调用应该是这样的。

var result = (from e in (A.Concat(B))
              where !B.Contains(e) || !A.Contains(e)
              select e).ToList();`

ToList()方法将LINQ查询转换为列表。

相关问题