Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
370 views
in Technique[技术] by (71.8m points)

linq - Compare two lists C#

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...