2012-08-15 29 views
4

現在我無法解決幾個小時的問題。 這是一個簡化的場景。 假設有一個人出價列表。我試圖找到出價最高的人並返回姓名。我能夠找到最高出價,但是如何輸出名稱?C#在字符串列表中查找元素

 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,這是正確的,但我需要顯示「鮑勃」來代替。有list.Select()這麼多的組合,但沒有成功。請人嗎?

+3

爲什麼不使用詞典? – Daniel 2012-08-15 13:31:03

+2

而不是使用字典,它可能會更聰明,使用一個類。查看Michel Keijzers的回答 – Manuzor 2012-08-15 13:39:28

回答

2

應該工作:

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

非常感謝,這是我一直在尋找的答案!也許不像定義一堂課那樣優雅,但我真的試圖避免它。乾杯! – Alex 2012-08-15 13:47:37

9

從一個角度建築點的最佳解決方案是創建一個包含兩個屬性名稱和每個人的出價和一類人單獨的類(例如人),其包含人員名單。

然後你可以很容易地使用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 2012-08-15 13:49:51

+1

您在那裏使用的最大值方法是否返回i​​nt? – 2012-08-15 13:51:56

+0

完全沒有問題......無論如何,我擴展了答案,以向其他人展示課程如何幫助提高可讀性和分擔責任。 – 2012-08-15 13:52:12

2

發現結果後只是做如下:

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

這在簡單的例子中工作。不知道真正的一個

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