2014-07-04 53 views
0

我有一個程序,我在其中添加對象到字典。字典是用int和我自定義的'Ship'類設置的。問題是我需要通過班級中的變量來組織船隻。基於類元素組織字典

船類 -

public class Ship 
{ 
    public string Name { get; set; } 
    public int Attack { get; set; } 
    public int Engine { get; set; } 
    public int Shield { get; set; } 
    public string Team { get; set; } 
    public string ShipClass { get; set; } 

    public Ship(string name, int attack, int engine, int shield, string team, string shipClass) 
    { 
     Name = name; 
     Attack = attack; 
     Engine = engine; 
     Shield = shield; 
     Team = team; 
     ShipClass = shipClass; 
    } 
} 

我需要通過ShipList [I] .Engine其中i下降至每艘船我要組織

Dictionary<int,Ship> ShipList = new Dictionary<int,Ship>(); 

。 任何幫助將是偉大的。

回答

0

A Dictionary是無序的,因此在嘗試對字典進行排序並將其保存在字典中是沒有意義的。這會給你的鍵/值(INT /艦)對的List,通過Engine下令:

var orderedPairs = ShipList.OrderBy(x => x.Value.Engine).ToList(); 
+0

謝謝,這正是我一直在尋找。 – GiantDwarf

0

這將爲您提供一個有序集合。請注意,如果您不需要對所有船舶進行排序,則應該用一個where子句來限制它,以減少排序所有船隻的開銷。

ShipList.Values.OrderBy(s => s.Attack); 
0

如果你想確定實際的字典是有序的,你需要使用SortedDictionary類來代替並提供你自己的IComparer。標準字典不支持按鍵排序。