如何追加独特数字,字符串列表 [英] How to append unique numbers to a list of strings

查看:105
本文介绍了如何追加独特数字,字符串列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个功能,它的工作原理并给出正确的结果:

I have this function, which works and gives the correct result:

  <System.Runtime.CompilerServices.Extension()>
  Public Function Unique(List As List(Of String)) As List(Of String)
    Return List.Select(Function(x, index) x & System.Text.RegularExpressions.Regex.Replace((List.GetRange(0, index).Where(Function(y) y = x).Count + 1).ToString, "\b1\b", String.Empty)).ToList
  End Function

此功能追加一个2,3,等可以根据需要,对那些没有独特的项目,以使它们是唯一的。

This function appends a "2", "3", etc as needed, to those items that are not unique, to make them unique.

如何删除正则表达式,而一)住在同一个LINQ声明(的code同一条线路),b)在不引入循环或c)评价前pression两次,因为会在 IIF 语句需要?

How can I remove the regex while a) staying in the same linq statement (the same line of code), b) without introducing a loop or c) evaluating the expression twice, as would be needed in an IIF statement?

这是不是<一个副本href="http://stackoverflow.com/questions/6509748/getting-index-of-duplicate-items-in-a-list-in-c-sharp">Getting在C#中列表中的重复项指标,因为:a)我的列表中没有的功能时改变和b)这个问题并没有一个准备申请code例子回答了,在这里我期待对于某个特定修正至code特定行。这些问题的答案不会解决我的问题;他们并不适用于此。

This is not a duplicate of Getting index of duplicate items in a list in c#, because a) my list does not change during the function and b) that question was not answered with a ready to apply code example, and here I'm looking for a specific fix to a specific line of code. Those answers will not fix my issue; they do not apply here.

推荐答案

您可以用做 GROUPBY ,如果你想preserve原来的顺序可以创建一个匿名类型,包括它,然后组,然后重新排序的原始顺序。

You could do it using GroupBy and if you want to preserve the original order you can create an anonymous type to include it, then group, then re-sort by the original order.

    string[] input = new[]{ "Apple", "Orange", "Apple", "Pear", "Banana", 
                            "Apple", "Apple", "Orange" };

    var result = input
        // Remember the initial order
        .Select((name, i) => new {name, i})
        .GroupBy(x => x.name)
        // Now label the entries in each group
        .SelectMany(g => g.Select((item, j) => 
            new {i = item.i, name = (j == 0 ? item.name : item.name + (j+1))}))
        // Now reorder them by their original order
        .OrderBy(x => x.i)
        // Remove the order value to get back to just the name
        .Select(x => x.name)
        .ToList();


    foreach (var r in result)
        Console.WriteLine(r);

结果

Apple
Orange
Apple2
Pear
Banana
Apple3
Apple4
Orange2

这篇关于如何追加独特数字,字符串列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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