C#:使用添加的数字重命名/替换列表中的重复项 [英] C#: Rename/replace duplicates in list with an added number

查看:137
本文介绍了C#:使用添加的数字重命名/替换列表中的重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个List<string>,我想在其中用所有添加的数字替换所有重复项.一个例子是:

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"}

我希望每个"Ply0"都具有唯一的名称,因此将其替换为"Ply0_1""Ply0_2".重要的是列表的顺序保持不变.之后,列表应如下所示:

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"}

我尝试过首先使用LINQ查找重复项,但是我是新手,在保持原始列表的顺序的同时,也很难用添加的数字替换它们.

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.

任何帮助将不胜感激!

推荐答案

使用linq,可以像这样完成操作,但我认为可读性不强

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();

这篇关于C#:使用添加的数字重命名/替换列表中的重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆