问题
I have a List<string>
where I would want to replace all duplicates with an added number to them. An example would be:
{"Ply0", "Ply+45", "Ply-45", "Ply0"}
I would like each "Ply0"
to have a unique name, so replace them with "Ply0_1"
and "Ply0_2"
. It is important that the order of the list stays the same. Afterwards the list should look like this:
{"Ply0_1", "Ply+45", "Ply-45", "Ply0_2"}
I have tried first finding the duplicates with LINQ but I am new to it and also have trouble replacing them with the added number while keeping the order of the original list.
Any help would be greatly appreciated!
回答1:
Using linq, it can be done like this, but i don't think it is much readable
var listx = new List<string>() { "Ply0", "Ply+45", "Ply-45", "Ply0" };
var res = listx.Select((s, i) => new { orgstr=s, index = i })
.GroupBy(x => x.orgstr)
.SelectMany(g => g.Select((x, j) => new { item = x, suffix = j + 1, count = g.Count() }))
.OrderBy(x => x.item.index)
.Select(x => x.count == 1 ? x.item.orgstr : x.item.orgstr + "_" + x.suffix)
.ToList();
来源:https://stackoverflow.com/questions/51004408/c-rename-replace-duplicates-in-list-with-an-added-number