[英]Using custom object as dictionary key but get values by object property
我有一節課:
public class Foo
{
public string Name { get; set; }
public double Value { get; set; }
public override string ToString()
{
return Name;
}
}
我需要創建一個字典,其中key是Foo的對象。 像這樣:
Foo foo1 = new Foo { Name = "Foo1", Value = 2.2 };
Foo foo2 = new Foo { Name = "Foo2", Value = 3.6 };
Dictionary<Foo, int> dic = new Dictionary<Foo, int>();
dic.Add(foo1, 1234);
dic.Add(foo2, 2345);
現在我想通過傳遞Foo.Name屬性作為鍵從字典中獲取值。 像這樣:
int i=dic["Foo1"];
// i==1234
i = dic["Foo2"];
// i==2345
可能嗎? 或者將Foo的對象作為鍵傳遞並覆蓋Equals方法的唯一方法?
如果使用Foo
作為鍵,則還需要使用Foo
來索引字典。
如果您實際需要的很可能是Dictionary<string, int>
,您可以嘗試重寫GetHashCode
和Equals
以便您可以僅根據名稱比較Foo
對象:
using System.Collections.Generic;
public class Foo {
public string Name { get; set; }
public double Value { get; set; }
public override string ToString() {
return Name;
}
public override int GetHashCode() {
return Name.GetHashCode();
}
public override bool Equals(object obj) {
Foo other = obj as Foo;
if (other == null) {
return false;
}
return Name.Equals(other.Name);
}
}
class Program {
static void Main(string[] args) {
Foo foo1 = new Foo { Name = "Foo1", Value = 2.2 };
Foo foo2 = new Foo { Name = "Foo2", Value = 3.6 };
Dictionary<Foo, int> dic = new Dictionary<Foo, int>();
dic.Add(foo1, 1234);
dic.Add(foo2, 2345);
int i = dic[new Foo { Name = "Foo1" }];
}
}
這個怎么樣:
class Program
{
public class Foo
{
public string Name { get; set; }
public double Value { get; set; }
public override string ToString()
{
return Name;
}
}
static void Main(string[] args)
{
Foo foo1 = new Foo { Name = "Foo1", Value = 2.2 };
Foo foo2 = new Foo { Name = "Foo2", Value = 3.6 };
var dic = new Dictionary<string, KeyValuePair<Foo, int>>();
dic.Add(foo1.Name, new KeyValuePair<Foo, int>(foo1, 1234));
dic.Add(foo2.Name, new KeyValuePair<Foo, int>(foo2, 2345));
int x = dic["Foo1"].Value;
var y = dic["Foo2"].Value;
Console.WriteLine(x);
Console.WriteLine(y);
Console.ReadKey();
}
}
結果將是:
1234
2345
Dictionary
基於哈希表,這意味着它使用哈希查找,這是一種查找事物的相當有效的算法。 我建議你考慮你的設計,如果你只想使用string
作為key
,只需使用Dictionary<string,int>
作為一種解決方法(只有當你不能改變你的設計時才使用這種方法),你可以做到這一點。
var key = dic.Keys.FirstOrDefault(c=>c.Name == "Foo1");
if(key != null)
dic[key]; //
好。 我通過創建一個繼承Dictionary和重寫get value方法來解決它。 這解決了我的問題,但我不確定大型集合的生產力。
public class MyDictionary:Dictionary<Foo, int>
{
public Bar():base()
{
}
new public int this[string key]
{
get
{
return this[base.Keys.Single(a => a.Name == key)];
}
}
}
然后這段代碼效果很好:
MyDictionary<Foo, int> dic = new MyDictionary<Foo, int>();
dic.Add(foo1, 1234);
dic.Add(foo2, 2345);
int i=dic["Foo1"];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.