Compare two lists C#

喜欢而已 提交于 2019-12-13 10:52:13

问题


I am having two lists

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 are in a but not in b so they are set to false whereas
  • 3 is in both the lists so its not in the output and
  • '4' is in b but not in a so they are set to true

the return type is a List<modelClass> that has int id, bool isTrue properties

Can you help me?


回答1:


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) });

With HashSet usage:

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) });


来源:https://stackoverflow.com/questions/26251091/compare-two-lists-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!