【问题标题】:Selecting items from list A which are not in List B and vice versa [duplicate]从列表A中选择不在列表B中的项目,反之亦然[重复]
【发布时间】:2021-08-14 08:51:29
【问题描述】:

我有两个AB 列表,并试图从A 中获取不在B 中的元素,从B 中获取不在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]。

我可以尝试什么来解决这个问题?

【问题讨论】:

  • 在查询后添加.ToList(),告诉查询将结果转换为列表。你也不需要List&lt;string&gt;演员
  • 所以基本上是异或? A 或 B 中的项目,但不是两者都有?
  • 是异或..
  • 我将其标记为重复,即使您的工作有效,如果您调用 ToList 或删除演员表到 List&lt;string&gt;

标签: c# linq


【解决方案1】:

你可以使用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}

【讨论】:

  • 刚刚尝试解决这个问题,看到了 S.Akbari 的解决方案,尝试了一下。它工作了 +1
【解决方案2】:

关于你的施法错误,调用应该是这样的。

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

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

【讨论】:

  • 嗯.. 我的错。谢谢:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-25
  • 1970-01-01
  • 1970-01-01
  • 2016-04-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多