C#: Rename/replace duplicates in list with an added number

↘锁芯ラ 提交于 2019-12-13 08:21:41

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!