[英]C# Reference object in a collection by a string instead of integer
我有一個存儲在List中的對象集合。
我想通過使用字符串名稱而不是整數來解決對象。
List<Foo> fooList = new List<Foo>;
Foo item = fooList["Foo Name"]
代替:
List<Foo> fooList = new List<Foo>;
Foo item = fooList[0]
我在想我需要創建一個繼承自List的集合類,但從那里開始,我不確定。
Dictionary<string, Foo>
是您想要的類型。
Joren的答案是首選,但是如果你需要保留其他邏輯的順序,並且你想要引用的對象的名稱可以是該對象的成員,那么Linq也可以做到這一點:
List<Foo> fooList = new List<Foo>;
Foo item = fooList.FirstOrDefault(f=>f.Name == "Foo Name");
您可以將其放入從列表派生的自定義集合的“索引器”屬性中:
public class MyList:List<Foo>
{
public Foo this[string name]
{
get { return this.FirstOrDefault(f=>f.Name == "Foo Name"); }
}
}
...它允許您獲得精確的所需語法,同時保持順序排序(字典無法保證)
你可以使用Dictionary<string,Your_Object_type>;
由於您不關心順序,這是最簡單的方法。
您始終可以使用詞典。 然后你可以這樣做:
var fooList = new Dictionary<string, Foo>();
fooList.Add("Foo Name", new Foo());
var item = fooList["Foo Name"];
而不是List<T>
,你需要一個Dictionary<TKey, TValue>
。
Dictionary<string, Foo> fooDictionary = new Dictionary<string, Foo>();
fooDictionary.Add("Foo Name", new Foo());
Foo myFoo = fooDictionary["Foo Name"];
你需要編寫自己的索引器
public datat-type this[int x]
{
get{
//getter code
}
set{
//Setter code
}
}
public data-type this[string x]
{
get{
//setter code
}
set{
//setter doe
}
}
可以將List.Find與謂詞一起使用,而不是使用字典。 請注意,這是字典的替代方法,但可以靈活地找到項(對象)的方式。 Name將是Foo的字符串屬性。
例:
List<Foo> fooList = new List<Foo>;
Foo item = fooList["Foo Name"]
//Find Using Inline
Foo foo = fooList.Find(delegate(Foo f) { return f.Name == "Foo Name"; });
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.