Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 从列表A中选择不在列表B中的项目,反之亦然_C#_Linq - Fatal编程技术网

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

C# 从列表A中选择不在列表B中的项目,反之亦然,c#,linq,C#,Linq,我有两个A和B列表,试图从A中获取不在B中的元素,以及从B中获取不在A中的元素 下面是我解决这个问题的尝试 var result = (List<string>)(from e in (A.Concat(B)) where !B.Contains(e) || !A.Contains(e) select e); var结果=(列表)(从e到A.Concat(B)) 其中!B.包含(e)| |!A.包含(e) 选择e); 遇到以下错误 无法强制转换类型为的对象 其中Enumerabl

我有两个
A
B
列表,试图从
A
中获取不在
B
中的元素,以及从
B
中获取不在
A
中的元素

下面是我解决这个问题的尝试

var result = (List<string>)(from e in (A.Concat(B))
where !B.Contains(e) || !A.Contains(e)
select e);
var结果=(列表)(从e到A.Concat(B))
其中!B.包含(e)| |!A.包含(e)
选择e);
遇到以下错误

无法强制转换类型为的对象 其中EnumerableIterator1[System.String]要键入 System.Collections.Generic.List`1[System.String]


非常感谢您的帮助。

您可以使用
,除了

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}
List firstList=新列表{1,2,3,4};
List secondList=新列表{1,5};
IEnumerable res=secondList.Except(firstList).Concat(firstList.Except(secondList));
//结果=>{5,2,3,4}

您可以使用
,但
除外:

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}
List firstList=新列表{1,2,3,4};
List secondList=新列表{1,5};
IEnumerable res=secondList.Except(firstList).Concat(firstList.Except(secondList));
//结果=>{5,2,3,4}

关于您的演员错误,通话应该是这样的

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

方法将LINQ查询转换为列表

关于您的演员错误,通话应该是这样的

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

方法将LINQ查询转换为列表

在查询后添加
.ToList()
,告知查询将结果转换为列表。您也不需要
列表
cast,所以基本上是一个排他or?A或B中的项,但不是两者都有?是的,排除或..我将其标记为重复项,即使您的项在查询后cal
ToList
或删除对
List
的强制转换以告诉查询将结果转换为列表时也有效。您也不需要
列表
cast,所以基本上是一个排他or?A或B中的项目,但不是两者都有?是的,独占的或..我将其标记为重复项,即使您的项目可以工作,如果您选择cal
ToList
或将强制转换移除到
List
Hmm。。我的错。谢谢:)嗯。。我的错。谢谢:)刚刚试着解决这个问题,看到了S.Akbari的解决方案,试过了。它起作用了+1只是试图解决这个问题,看到了S.Akbari的解决方案,尝试了一下。它成功了+1