miller
miller

Reputation: 1728

How to find duplicates in list and sort them by number of appearance

Is there a easy way to find duplicates in list, and then sort them by number of appearance? Also, duplicates should be removed.

Eg. you have a List<String> like this:

List<String> = new List<String>{"6","1","2","2","4","6","5","1","6","6","2"};

Question is, how to convert this list into -> "6", "1", "2", "4", "5"?

Upvotes: 1

Views: 2849

Answers (6)

svick
svick

Reputation: 244928

I think the simplest way is to use LINQ method Distinct():

var originalList = …;
vat withoutDuplicates = originalList.Distinct();

Though you should note that the order of the result of Distinct() is explicitly left undocumented.

Upvotes: 2

D Stanley
D Stanley

Reputation: 152596

Since it's unclear exactly what you mean, here's a solution for two possible meanings:

  1. Get a unique list ordered by the number of occurrences:

    Group the list and sort by Count():

    List<String> list = new List<String>{"6","1","2","2","4","6","5","1","6","6","2"};
    
    var q = from s in list
    group s by s into g
    orderby g.Count() descending
    select g.Key;
    
  2. Get a unique list ordered by the FIRST occurrence of the item in the list

    There are already several suggestions to use Distinct, however the documentation DOES NOT GUARANTEE that they appear in the order they appear in the list (the current Enumerable implementation happens to order them that way, but for other providers it's not guaranteed):

    Remarks
    The result sequence is unordered.

    To guarantee order, add an OrderBy clause:

    var q = list.Distinct().OrderBy(s => list.IndexOf(s));
    

Upvotes: 0

Nathan Koop
Nathan Koop

Reputation: 25197

Not quite the cleanest yet, but this provides the correct result.

var originalData = new List<string>{"6","1","2","2","4","6","5","1","6","6","2"};
var result = new List<string>();

foreach (var myString in originalData)
{
    if (!result.Exists(s => s == myString))
        result.Add(myString);
}

Upvotes: 0

Rawling
Rawling

Reputation: 50144

If you actually want them ordered from most common to least - unlike your example -

var ordered = list
    .GroupBy(i => i)
    .OrderByDescending(g => g.Count())
    .Select(g => g.Key);

should achieve this.

Upvotes: 2

user1639464
user1639464

Reputation:

Using System.Linq;
// Assuming inputList was the original string list
List<String> deDuped = inputList.Distinct().ToList();

Upvotes: 0

burning_LEGION
burning_LEGION

Reputation: 13450

use Linq.Distinct()

List<String> list = new List<String>{"6","1","2","2","4","6","5","1","6","6","2"};
list = list.Distinct().ToList();

Upvotes: 2

Related Questions