Last active
July 23, 2025 15:34
-
-
Save rpresser/71b9ee973c946e21f4b3af653cb21cec to your computer and use it in GitHub Desktop.
Uniquify Names in a list of objects with a Name property, by appending _2, _3, etc.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
void Main() | |
{ | |
// Define the list | |
var coll = new List<Foo> | |
{ | |
new Foo { Name = "ross", Description = "me" }, | |
new Foo { Name = "joel", Description = "also me" }, | |
new Foo { Name = "ross", Description = "me #2" }, | |
new Foo { Name = "ross", Description = "me #3" }, | |
new Foo { Name = "joel", Description = "also me #2" } | |
}; | |
// Rename duplicates by grouping and indexing | |
var renamed = coll | |
.GroupBy(c => c.Name.ToUpperInvariant()) | |
.SelectMany(g => g.Select((c, i) => new { | |
Foo = c, | |
NewName = i == 0 ? c.Name : $"{c.Name}{i + 1}" | |
})); | |
// rename each item that needs renaming | |
foreach (var item in renamed) | |
{ | |
item.Foo.Name = item.NewName; | |
} | |
// in LINQPad, Output the result | |
coll.Dump("Renamed Collection"); | |
// if using in another app, you'd return the collection at this point. | |
} | |
// Class definition. Could possibly be helpful for this to be an interface providing a Name property | |
// and nothing else, to be used with any other class | |
public class Foo | |
{ | |
public string Name { get; set; } | |
public string Description { get; set; } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment