【问题标题】:Pick the lowest element in a list [duplicate]选择列表中的最低元素[重复]
【发布时间】:2019-06-01 12:42:04
【问题描述】:

我想根据大小选择媒体,但似乎无法弄清楚如何以一种聪明的方式选择内存消耗最低的媒体。

内存使用情况存储在Size字段中。

using System;
using System.Collections.Generic;

struct placeholder
{
    string size;

    public placeholder(string input)
    {
        this.size = input;
    }
}

public class Program
{
    public static void Main()
    {
        List<placeholder> list = new List<placeholder>();
        list.Add(new placeholder("1"));
        list.Add(new placeholder("2"));
        list.Add(new placeholder("3"));
        list.Add(new placeholder("4"));

        // How to find the entry in list with lowest placeholder.size?
        Console.WriteLine("Hello World");
    }
}

但是如何选择内存最低的,大小存储为字符串?

我可以做一个 for 循环,但是有什么更聪明的方法吗?

【问题讨论】:

  • 首先,将Size 设为公开以便您可以访问它,然后将其设为数字​​以便您可以正确评估它。 "9"(字符串)的计算结果总是大于 "100"
  • 副本找到最大值。你应该能够应付。

标签: c# string linq int min


【解决方案1】:

没有什么比浏览列表更聪明的了。期间。

它是一个 LIST - 它没有关于特殊条件的内在魔法知识,因此要找到一个匹配特定条件(最低记忆)的元素,您必须遍历所有元素并评估它们。周期 - 内在的基本逻辑,这里没有什么聪明的可能。

获取每个元素,将大小与存储的最小元素大小进行比较,如果最小元素更小,则替换最小元素(并定义在相同大小上做什么)。

【讨论】:

    【解决方案2】:

    无论您采用哪种解决方案,您都无法避免“访问”整个列表的每个元素,因为为了获得最小项目,您需要与其他所有项目进行比较。

    你可以通过 Linq Aggregate 得到结果:

    var min = list.Aggregate((l, r) => int.Parse(l.size) > int.Parse(r.size) ? r : l);
    

    或使用典型的 for 循环。

    【讨论】:

    • 比较字符串是不够的(“2”>“10”)。
    • @GertArnold 已编辑。此外,由于size 表示整数,因此首先将size 作为int 可能更合适。
    • 是的,这或多或少是重复的。
    【解决方案3】:

    此问题的典型解决方案是对列表进行排序,然后根据您的排序算法获取第一项或最后一项。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-30
      • 1970-01-01
      • 1970-01-01
      • 2018-11-11
      • 2018-04-29
      • 2021-03-02
      • 2021-06-21
      • 1970-01-01
      相关资源
      最近更新 更多