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