c# - 如何返回另一个列表中三个最低值的列表

标签 c# list

如何返回另一个列表中 3 个最低值的列表。例如,我想像这样获得 3 个最低值:

in_list = [2, 3, 4, 5, 6, 1]

为此:

out_list: [2, 3, n, n, n, 1]

也许是这样的功能:

out_list = function(in_list, 3)?

in_list 和输出列表声明如下:

List<string> in_list = new List<string>();
List<string> out_list = new List<string>();

你能帮我开发一个 C# 代码吗?可以给出进一步的解释。

最佳答案

如果你真的想要那些奇怪的n,有这个简单的解决方案:

public static List<string> Function(List<string> inputList, int max)
{
    var inputIntegers = inputList
        .Select(z => int.Parse(z))
        .ToList();

    var maxAuthorizedValue = inputIntegers
        .OrderBy(z => z)
        .Take(max)
        .Last();

    return inputIntegers
        .Select(z => z <= maxAuthorizedValue ? z.ToString() : "n")
        .ToList();
}

public static void Main(string[] args)
{
    List<string> in_list = new List<string> { "2", "3", "4", "6", "1", "7" };

    var res = Function(in_list, 3);

    Console.Read();
}

对于重复项的新要求,您可以限制返回的整数的最大数量:

public static List<string> Function(List<string> inputList, int max)
{
    var inputIntegers = inputList.Select(z => int.Parse(z)).ToList();

    var maxAuthorizedValue = inputIntegers
        .OrderBy(z => z)
        .Take(max)
        .Last();

    // I don't really like that kind of LINQ query (which modifies some variable
    // inside the Select projection), so a good old for loop would probably
    // be more appropriated
    int returnedItems = 0;
    return inputIntegers.Select(z =>
        {
            return (z <= maxAuthorizedValue && ++returnedItems <= max) ? z.ToString() : "n";
        }).ToList();
}

关于c# - 如何返回另一个列表中三个最低值的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33346072/

相关文章:

c#,要处理的面板中的控件

c# - 查找枚举中的最大值

python - 基于Python中的键聚合字典列表上的值

sql-server - List(of T) 与 DataTable 填充数据库

c# - 命令绑定(bind) WPF

c# - 通过单击任何地方/任何其他地方从 TextBox 中删除焦点

c# - 限制在 C# 中使用结构

java - List remove(Object object) 何时以及为何返回 false

python - 根据给定顺序对列表进行排序

java - Javers 比较不同顺序的列表