【问题标题】:C# Finding element in List of String ArraysC# 在字符串数组列表中查找元素
【发布时间】:2012-08-15 13:28:37
【问题描述】:

我现在几个小时都无法解决问题。 这是一个简化的场景。 假设有一个人的出价列表。我正在尝试找到出价最高的人并返回名称。我可以找到最高的出价,但我如何输出名称?

        List<String[]> list = new List<String[]>();
        String[] Bob = { "Alice", "19.15" };
        String[] Alice = {"Bob", "28.20"};
        String[] Michael = { "Michael", "25.12" };

        list.Add(Bob);
        list.Add(Alice);
        list.Add(Michael);

        String result = list.Max(s => Double.Parse(s.ElementAt(1))).ToString();

        System.Console.WriteLine(result);

结果我得到 28.20,这是正确的,但我需要改为显示“Bob”。 list.Select() 有很多组合,但没有成功。请问有人吗?

【问题讨论】:

  • 与其使用字典,不如为此使用类更明智。查看 Michel Keijzers 的回答

标签: c#


【解决方案1】:

从架构的角度来看,最好的解决方案是创建一个单独的类(例如 Person),其中包含每个人的两个属性 Name 和 Bid,以及一个包含人员列表的 Persons 类。

然后您可以轻松使用 LINQ 命令。

除了将出价存储为字符串之外,还可以考虑将出价存储为浮点数或十进制值会更好(或将其存储为美分并使用 int)。

我没有手动编译器,所以有点想不通:

public class Person
{
    public string Name { get; set; }
    public float  Bid  { get; set; }

    public Person(string name, float bid)
    {
        Debug.AssertTrue(bid > 0.0);
        Name = name;
        Bid = bid;
    }
}

public class Persons : List<Person>
{
    public void Fill()
    {
        Add(new Person("Bob", 19.15));
        Add(new Person("Alice" , 28.20));
        Add(new Person("Michael", 25.12));
    }
}

在你的课堂上:

var persons = new Persons();
persons.Fill();

var nameOfHighestBidder = persons.MaxBy(item => item.Bid).Name;
Console.WriteLine(nameOfHighestBidder);

【讨论】:

  • 我同意,上课会更容易处理。但由于问题的性质(网络服务等),我不想创建额外的类。感谢您的宝贵时间!
  • 你在那里使用的 Max 方法不返回一个 int 吗?
  • 完全没有问题...我扩展了答案以向其他人展示类如何帮助提高可读性和拆分职责。
  • 我将 Max 更改为 MaxBy,假设它返回出价最高的人,然后取那个人的名字。
  • MoreLinq吗?我不记得 .NET Framework 中的 MaxBy
【解决方案2】:

这适用于简单的示例。不知道是不是真的

var result = list.OrderByDescending(s => Double.Parse(s.ElementAt(1))).First();

【讨论】:

    【解决方案3】:

    您可以使用Jon Skeet's MaxBy.

    用法可以看this question 例如在这种情况下

    list.MaxBy(s => Double.Parse(s.ElementAt(1)))[0]
    

    更多here

    【讨论】:

      【解决方案4】:

      应该有效:

      var max = list.Max(t => double.Parse(t[1]));
      list.First(s => double.Parse(s[1]) == max)[0]; // If list is not empty
      

      【讨论】:

      • 非常感谢,这就是我要找的答案!也许不像定义一个类那样优雅,但我真的试图避免它。干杯!
      【解决方案5】:

      找到结果后,请执行以下操作:

      list.First(x=>x[1] == result)[0]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-02-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多