Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rename duplicates in list using LINQ

Tags:

c#

linq

I need a list of unique values. But it could be, the values exists twice or more in the list. If this occurs I must rename the value but the renamed value also could be in the list.

It is possible to rename the values using a LINQ query so i don't need a sub-query?

example 1: before: "one", "one", "two", "two", "three" after: "one", "one_", "two", "two_", "three"

example 2: before: "one", "one", "one_" after: "one", "one_", "one__"

The 3rd "one" has 2 underscores because the 2nd "one" was renamed to "one_".

Thanks a lot for an idea...

like image 290
Rocco Hundertmark Avatar asked Dec 06 '22 19:12

Rocco Hundertmark


1 Answers

I don't think this should be done with simply a linq-query. I'd use a HashSet and create a function if I was you. Something like this:

IEnumerable<String> GetUnique(IEnumerable<String> list) {
    HashSet<String> itms = new HashSet<String>();
    foreach(string itm in list) {
         string itr = itm;
         while(itms.Contains(itr)) {
             itr = itr + "_";
         }
         itms.Add(itr);
         yield return itr;
    }
}

[Edit]

This could be made into an extension-method though, so you could call it like this: myList.GetUnique(); (or something like that)

[Edit 2]

Fixed bug with iterator-variable being changed.

like image 169
Alxandr Avatar answered Dec 10 '22 01:12

Alxandr