Last active
December 19, 2019 20:06
Uniquify Names in a list of objects with a Name property, by appending _2, _3, etc.
This file contains 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
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