2012-02-15 69 views
0

我想實現一個包含我的類的實例的自定義集合。如何通過屬性名稱訪問自定義集合屬性

這是我的課,這裏有點簡化。

public class Property : IComparable<Property> 
{ 
    public string Name; 
    public string Value; 
    public string Group; 
    public string Id; 
    ... 
    ... 

    public int CompareTo(Property other) 
    { 
     return Name.CompareTo(other.Name); 
    } 
} 

我加入房產的情況下,以列表的收集

Public List<Property> properties; 

我可以通過屬性迭代或通過索引位置訪問特定的屬性。

我想但是能夠通過它的名稱,使得

var myColor = properties["Color"].Value; 

訪問屬性,我沒有一個有效的方法來做到這一點。我假設屬性應該寫成一個自定義列表集合類來實現這一點。有沒有人有我可以看的代碼示例?

感謝您的幫助。

+0

你還是希望能夠使用索引來訪問它們?或者是通過名稱訪問足夠? – SWeko 2012-02-15 07:34:34

+0

按名稱訪問並迭代集合比按索引訪問對象更常見。 – MWS 2012-02-15 07:52:30

回答

1

最簡單的方法已經提到,但我看到兩個:

方法1 轉換爲字典,查找存在。

var props = properties.ToDictionary(x => x.Name); 
Property prop = props["some name"]; 

方法2 創造條件,由您任意類型支持索引 自己的集合類型。

public class PropertyCollection : List<Property> 
{ 
    public Property this[string name] 
    { 
     get 
     { 
      foreach (Property prop in this) 
      { 
       if (prop.Name == name) 
        return prop; 
      } 
      return null; 
     } 
    } 
} 

,並使用此集合,而不是

PropertyCollection col = new PropertyCollection(); 
col.Add(new Property(...)); 
Property prop = col["some name"]; 
+0

使用索引器在這裏真的很好。 – PraveenLearnsEveryday 2012-02-15 07:42:25

+0

方法2可能是我正在尋找的。迭代對使用索引有什麼重大影響?我的收藏將不會擁有超過30個物業實例。 – MWS 2012-02-15 07:54:44

1

你可以使用一個Dictionary

Dictionary<string, Property> properties = new Dictionary<string, Property>(); 

//you add it like that: 
properties[prop.Name] = prop; 

//then access it like that: 
var myColor = properties["Color"]; 
+0

名稱,值是我的Property類的簡化版本。我應該提到它,它有其他成員。 – MWS 2012-02-15 07:47:34

0

使用Dictionary<string,Property>用於這一目的。密鑰將是屬性名稱,值將是Property實例本身。