在C#中查找字符串数组列表中的元素

4

我现在已经几个小时没能解决一个问题了。下面是一个简化的场景。 假设有一个人员名单,以及他们的报价。我正在尝试找到报价最高的那个人,并返回其姓名。我已经能够找到最高的报价,但如何输出该人的姓名呢?

        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()的组合,但都没有成功。请问有人能帮忙吗?

2
不要使用字典,使用类可能更明智。查看Michel Keijzers的答案。 - Manuzor
5个回答

9

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

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

此外,不要将出价存储为字符串,思考一下将其作为浮点或十进制值更好(或将其存储在分为单位的整数中)。

我手头没有编译器,所以有些东西需要自己补充。

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);

1
我同意,使用类会更容易处理。但由于问题的性质(Web服务等),我不想创建额外的类。谢谢你的时间! - Alex
1
你在那里使用的Max方法不是返回一个整数吗? - Şafak Gür
完全没有问题...我还扩展了答案,以展示类如何帮助提高可读性和分离职责。 - Michel Keijzers
我将Max更改为MaxBy,假设它返回具有最高出价的人,然后获取该人的姓名。 - Michel Keijzers
MoreLinq 吗?我不记得在 .NET Framework 中有 MaxBy - Şafak Gür
@ŞafakGür 是的...请参考https://dev59.com/jHA75IYBdhLWcg3wo6rx#3188751 - Michel Keijzers

5

5

这在简单的例子中有效。不确定在真实情况中是否有效。

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

3

应该可以工作:

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

非常感谢,这正是我在寻找的答案!虽然不如定义类那般优雅,但我确实尽力避免了。干杯! - Alex

2
找到结果后,请按以下步骤操作:
list.First(x=>x[1] == result)[0]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接