15

I want to do the opposite thing as here

I have a list and I know how to remove the duplicates. But I want to have an option where the user can select which duplicate to keep. Some query quere I can have a list that will only show the duplicates. Something like:

Lets say my list is:

"tom" "bob" "Frank" "bob" "Lacey" "Frank"

I know that if I use the distinct method I will get:

"tom" "bob" "Frank" "Lacey"

I don't know what method to I have to use to get:

"bob" "bob" "frank" "frank"

or to get

"bob" "frank"

cause those are the ones that repeat.

4
  • 4
    Group by Name having count > 1 Commented May 25, 2011 at 17:08
  • In other words I want to do the same thing that iTunes does when you click on the option that says show duplicate songs. Commented May 25, 2011 at 17:08
  • @Joe: your answer match perfectly question asked. Why don't you post it as an answer to allow the OP to approve it? Commented May 25, 2011 at 17:11
  • @Sylverdrag I do not know LINQ well enough to provide an adequate answer Commented May 25, 2011 at 17:13

2 Answers 2

24

You can use GroupBy to filter out the items that only occur once, then flatten the remaining items back into a list:

var resultList = list.GroupBy(x => x)
                     .Where(g => g.Count() > 1)
                     .SelectMany(g => g)
                     .ToList();
Sign up to request clarification or add additional context in comments.

3 Comments

Also, slightly more efficient for the general case of an IEnumerable when having a large number of duplicates you could use .Where( g=> g.Skip(1).Any()) instead of the above Where condition.
Why do we need SelectMany after Where condition? I am new to Linq please help me out in understanding this.
@Sandeep: SelectMany "flattens" a list of lists to a single lists that consists of all the elements contained in the original lists
1

I needed to compare them by a specific property theretofore I just modified your query BrokenGlass to

var resultList = itemsThatNeedToBeAdded.GroupBy(x => x.property1)
                     .Where(g => g.Count() > 1 )
                     .SelectMany(g => g)
                     .ToList();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.