c# - 给定列表和种子的唯一名称

标签 c# linq unique

我的问题是在由“种子”组成的列表中生成一个新的唯一名称,一个连续的整数,重复使用具有相同种子的缺失索引。

我写下了下面的扩展

    /// <summary>
    /// Gets the Next Valid Index given a list of names and a root string.
    /// </summary>
    /// <param name="names">The list of just used names.</param>
    /// <param name="seedName">The string to be used as seed.</param>
    /// <returns>System.Int32 (One Based) with next valid Index.</returns>
    /// <Examble>
    /// Present Names:
    /// AA, AA1, AA2, BB, BB3
    /// With Seed AA, result is 3
    /// With Seed BB, result is 1
    /// With Seed CC, result is 1 (missing index is used)
    /// </Examble>
    public static int GetNextIndex(this List<string> names, string seedName)
    {
        var max = 0;
        var namesIndexes = new List<NameIndex>();

        names.ForEach(name =>
        {
            var m = Regex.Match(name, @"\d+");
            if (m.Success)
            {
                if (string.IsNullOrWhiteSpace(m.Value))
                {
                    namesIndexes.Add(new NameIndex(name, 0));
                }
                else
                {
                    var v = 0;
                    if (int.TryParse(m.Value, out v))
                        namesIndexes.Add(new NameIndex(name.Replace(m.Value, string.Empty), v));
                }
            }
            else
            {
                namesIndexes.Add(new NameIndex(name, 0));
            }
        });

        var grouped = namesIndexes.GroupBy(n => n.Name).ToDictionary(g => g.Key, g => g);
        if (grouped.ContainsKey(seedName))
        {
            max = grouped[seedName].Max(gn => gn.Index);
            var all = Enumerable.Range(1, max).ToList();
            var available = all.Except(grouped[seedName].Select(gn => gn.Index)).ToList();
            if (available.Any())
                return available.Min();
        }

        return max + 1;
    }

其中 NameIndex 是一个辅助类:

/// <summary>
/// Class NameIndex.
/// </summary>
public class NameIndex
{
    public string Name { get; set; }
    public int Index { get; set; }

    public NameIndex(string name, int index)
    {
        Name = name;
        Index = index;
    }
}

我的问题是:如何改进该功能?

感谢您的帮助!

最佳答案

看看这段代码是否适合你

public static int GetNextIndex(List<string> names, string seedName)
{
    var namesWithSeed = names.Where(n => !string.IsNullOrEmpty(n) && n.StartsWith(seedName));
    if (names.Count == 0)
        return 1;
    int temp = 0;
    var allIntsStringsForSeed = namesWithSeed
                                .Select(n => n.Replace(seedName, string.Empty))
                                .Select(s => int.TryParse(s, out temp) ? temp : 0)
                                .OrderBy(i => i)
                                .ToList();
    var idx = 0;
    for (int i = 0; i < allIntsStringsForSeed.Count; i++)
    {
        if (i == allIntsStringsForSeed.ElementAt(i))
            idx = i;
        else
            break;
    }
    return idx == 0 ? 1 : idx + 1;
}

测试

var strings = new List<string> { "AA", "AA1", "AA2", "BB", "BB3" };
var indexAA = GetNextIndex(strings, "AA"); //3
var indexBB = GetNextIndex(strings, "BB"); //1
var indexCC = GetNextIndex(strings, "CC"); //1

关于c# - 给定列表和种子的唯一名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33565470/

相关文章:

c# - 为什么在插入这些记录时会出现主键冲突? (EF4 代码优先)

c# - Valums Ajax 上传 w/C# ashx 返回 'Index was out of range. Must be non-negative and less than the size of the collection.' 错误

c# - 如何在 C# 中读取 JKS 文件

c# - 使用 Linq 获取列表 <> 的项目数

javascript唯一字符串数组不区分大小写,但保留一个区分大小写的结果

python - 二维 numpy 数组列中的唯一条目

c# - 将 Ruby 转换为 C#

c# - 如何从通用 IDictionary 获取 IDictionaryEnumerator?

c# - 也许在 Linq 中找到了一个功能。具有多个字段的 Groupby

mysql - 有没有办法使整个 MySQL 行唯一