I wrote this piece of code to append index to any duplicate entry in List<T>
like in the sample below.
Input
["dupe", "not dupe", "dupe", "also not dupe"]
Output
["dupe1", "not dupe", "dupe2", "also not dupe"]
But the problem is it's O(n^2)
in the second loop and I'm working on a large list (30+ items). I'm very new to C# and didn't know much built-in functions, so I wanted to know is there anything I can do to optimize this?
List<string> duplicate = new List<string>(); // For storing duplicate item
IEnumerable<IGrouping<string, string>> g = header.GroupBy(i => i);
// Find duplicate and store it in duplicate
foreach (var item in g)
if (item.Count() > 1)
duplicate.Add(item.Key);
// Loop through duplicate to append the index
foreach (var item in duplicate) {
int start = 1;
for (int i = 0; i < header.Count; i++) {
// If header[i] is a duplicate item append index to it.
if (string.Equals(header[i], item, StringComparison.OrdinalIgnoreCase)) {
header[i] = string.Format("{0}{1}", header[i], start);
start++;
}
}
}