首页 > 解决方案 > 如何使用字符串而不是int?在 C# 中

问题描述

我希望我可以将此代码与字符串而不是整数一起使用

public static List<int> EvenlyDistribute(List<int> list)
{
    List<int> original = list;

    Dictionary<int, int> dict = new Dictionary<int, int>();
    list.ForEach(x => dict[x] = dict.Keys.Contains(x) ? dict[x] + 1 : 1);

    list = list.Where(x => dict[x] == 1).ToList();

    foreach (int key in dict.Where(x => x.Value > 1).Select(x => x.Key))
    {
        int iterations = original.Where(x => x == key).Count();
        for (int i = 0; i < iterations; i++)
            list.Insert((int)Math.Ceiling((decimal)((list.Count + iterations) / iterations)) * i, key);
    }

    return list;
}

主要用途:

 List<int> test = new List<int>() {11,11,11,13,14,15,16,17,18,19,19,19,19};
 List<int> newList = EvenlyDistribute(test);

输出:

19,11,13,19,14,11,19,15,16,19,11,17,18

是否可以使用此方法但使用字符串?

标签: c#

解决方案


您可以替换int为泛型类型并将其替换为==.Equals以便它适用于任何类型(包括字符串):

public static List<T> EvenlyDistribute<T>(List<T> input)
{
    if (input == null || input.Count < 3) return input;

    var dict = input.Distinct().ToDictionary(
        key => key, value => input.Count(x => x.Equals(value)));

    input = input.Where(x => dict[x] == 1).ToList();

    foreach (var kvp in dict.Where(item => item.Value > 1))
    {
        decimal count = kvp.Value;

        for (var i = 0; i < count; i++)
        {
            input.Insert((int) (Math.Ceiling((input.Count + count) / count) * i), 
                kvp.Key);
        }
    }

    return input;
}

推荐阅读