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
701 views
in Technique[技术] by (71.8m points)

linq - Comparing two Lists and returning the distinct values and the differences

I have two lists:

List A {A, B, C, D}

List B {A, E, F, G}

I need to produce three lists:

One with the items only in list A

(B, C, D)

One with the items only in list B

(E, F, G)

One with the items in both

(A)

Given that the lists are actually registry keys, there could be a huge number of them so I can foresee a huge performance overhead if I choose to use traditional ForEach or For(int i...) methods.

I am not averse to these if they will do the job efficiently but I would prefer to use Linq.

Has anyone got any ideas?

I don't care about identical records.

I have already created an IEquatable<> class that will compare the elements, but it is how to use this to create my required outputs that I am struggling with.

Thanks in advance.

By the way I am using VS2012 with .NET 4.5

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)
var A = new List<string>() { "A", "B", "C", "D" };
var B = new List<string>() { "A", "E", "F", "G" };

A.Except(B).ToList()
// outputs List<string>(2) { "B", "C", "D" }
B.Except(A).ToList()
// outputs List<string>(2) { "E", "F", "G" }
B.Intersect(A).ToList()
// outputs List<string>(2) { "A" }

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

...