【问题标题】:How to append unique numbers to a list of strings如何将唯一数字附加到字符串列表
【发布时间】:2014-12-28 10:24:08
【问题描述】:

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

  <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”等附加到那些不唯一的项目,以使其唯一。

如何在 a) 保留在同一 linq 语句(同一行代码)中,b) 不引入循环或 c) 计算表达式两次时删除正则表达式,这在 IIF 语句中是必需的?

这不是 Getting index of duplicate items in a list in c# 的副本,因为 a) 我的列表在函数执行期间没有更改 b) 没有通过准备应用代码示例回答该问题,我正在寻找特定的修复到特定的代码行。这些答案不会解决我的问题;它们不适用于此处。

【问题讨论】:

  • 您是否关心保留订单,或者您可以使用GroupBy 收集所有具有相同标识符的订单,然后为组内的每个订单添加索引?
  • 是的,订单很重要。这些是 csv 文件中的标题,它们必须与行值匹配。谢谢

标签: .net linq


【解决方案1】:

您可以使用GroupBy 来完成它,如果您想保留原始顺序,您可以创建一个匿名类型来包含它,然后分组,然后按原始顺序重新排序。

    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

【讨论】:

  • 也许这很奇怪,也许不是,但我打算用一个苹果、两个香蕉和一个橙子来编辑我的问题。大声笑
  • 我印象深刻!非常聪明!我会研究这个直到我理解为止。
【解决方案2】:

这是 VB 版本:

  <System.Runtime.CompilerServices.Extension()>
  Public Function Unique(List As List(Of String)) As List(Of String)
    ' 1. Remember the initial order
    ' 2. Group by the text
    ' 3. Label the entries in each group
    ' 4. Now reorder them by their original order
    ' 5. Remove the order value to get back to just the name
    Return List.
      Select(Function(Item, Index) New With {Item, Index}).
      GroupBy(Function(IndexedItem) IndexedItem.Item).
      SelectMany(Function(Group) Group.Select(Function(GroupItem, GroupIndex) New With {.Index = GroupItem.Index, .UniqueItem = GroupItem.Item & If(GroupIndex = 0, String.Empty, (GroupIndex + 1).ToString)})).
      OrderBy(Function(IndexedUniqueItem) IndexedUniqueItem.Index).
      Select(Function(IndexedUniqueItem) IndexedUniqueItem.UniqueItem).
      ToList()
  End Function

【讨论】:

    猜你喜欢
    • 2018-02-28
    • 2012-12-05
    • 2012-09-14
    • 1970-01-01
    • 2012-01-12
    • 2018-09-13
    • 2018-09-25
    • 2012-07-12
    • 2016-03-22
    相关资源
    最近更新 更多