Skip to content

Instantly share code, notes, and snippets.

@rpresser
Last active December 19, 2019 20:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rpresser/71b9ee973c946e21f4b3af653cb21cec to your computer and use it in GitHub Desktop.
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.
class foo
{
public string Name { get; set; }
public string description { get; set; }
}
void Main()
{
List<foo> coll = new List<foo>();
coll.Add(new foo() { Name = "ross", description = "me" });
coll.Add(new foo() { Name = "joel", description = "also me" });
coll.Add(new foo() { Name = "ross", description = "me #2" });
coll.Add(new foo() { Name = "ross", description = "me #3" });
coll.Add(new foo() { Name = "joel", description = "also me #2" });
// coll now contains the equivalent of this:
// { {"Name": "ross", "Description": "me"}
// {"Name": "joel", "Description": "also me"}
// {"Name": "ross", "Description": "me #2"}
// {"Name": "ross", "Description": "me #3"}
// {"Name": "joel", "Description": "also me #2"} }
coll.GroupBy(c => c.Name.ToUpperInvariant())
.Select(g => g.Select((c, j) => new { foo = c, Name = (j == 0 ? c.Name : ($"{c.Name}_{j + 1}")) }))
.SelectMany(g => g)
.All(t => { t.foo.Name = t.Name; return true; });
// Note that no extra variables are defined, nor are any ToList() needed.
// There's also no need to track the original order, because we are modifying the original objects stored in the List!
// coll now contains the equivalent of this:
// { {"Name": "ross", "Description": "me"}
// {"Name": "joel", "Description": "also me"}
// {"Name": "ross2", "Description": "me #2"}
// {"Name": "ross3", "Description": "me #3"}
// {"Name": "joel2", "Description": "also me #2"} }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment