c# - 如何使用字符串而不是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
是否可以使用此方法但使用字符串?
解决方案
您可以替换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;
}
推荐阅读
- java - 如何对除 api 网关之外的所有人隐藏我的公共微服务?
- python-3.x - 尝试通过 kudu 控制台在 python azure 函数中添加模块(speech_py_impl),但面临虚拟环境问题
- c# - CommandBinding 使用自定义 ICommand 实现时未调用已执行的事件处理程序
- python - 在 Python 中使用 OpenCV 确定图像中所有圆形(重叠)斑点的半径
- python - 非均匀间距,带有 numpy.gradient 的多元导数
- jwt - Zoom API:帐户未启用 REST API
- maps - HERE 有 Parcel 边界数据吗?
- java - 如何在 Spring 中将 Redis Http 会话超时设置为无限制
- javascript - 将 python 脚本与 html 的 java 脚本混合
- visual-studio-code - Bash终端不允许打字