比较两个列表C# [英] Compare two lists C#
本文介绍了比较两个列表C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个列表
List<int> a = {1,2,3};
List<int> b = {3,4};
我需要以这样的方式比较它们,输出应该是
I need to compare them in such a way that the output should be
1 false
2 false
4 true
输出是通过使用以下逻辑
The output is by using the following logic
-
1,2
位于a
,但不在b
中,因此它们设置为false
,而 -
3
- '4'在
b
中,但不在a
中,因此设置为true
1,2
are ina
but not inb
so they are set tofalse
whereas3
is in both the lists so its not in the output and- '4' is in
b
but not ina
so they are set totrue
返回类型是 List< modelClass& 有
int id,bool isTrue
属性
p>
推荐答案
如果你不在乎性能,你可以使用下面的LINQ:
If you don't care about performance you can use the following LINQ:
a.Except(b)
.Union(b.Except(a))
.Select(item => new { id = item, isTrue = b.Contains(item) });
使用 HashSet
用法:
var setA = new HashSet<int>(a);
var setB = new HashSet<int>(b);
setA.SymmetricExceptWith(b);
var result = setA.Select(item => new { id = item, isTrue = setB.Contains(item) });
这篇关于比较两个列表C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文