2014-01-14 72 views
0

我想检索一个dictonary的关键属性,因为关键是一个类。你怎么做呢?下面是我使用的类:获取dictonary关键对象属性

public class Item 
{ 
    public int Sku { get; set; } 
    public string Name { get; set; } 

    public Item() 
    { 
    } 
} 

我想找回它的属性,例如Name

Dictionary<Item,double> myDictionary = new Dictionary<Item,double>(); 
Item item = new Item { Sku = 123, Name = "myItem" }; 
myDictionary.Add(item,10.5); 

所以现在例如如何从本字典我会检索项的NameSku,或任何其他财产,如果它有他们?

+0

使用GET方法来检索名字! –

+2

你确定你想要钥匙成为班级吗?为什么? –

+0

你究竟想做什么.. –

回答

1

首先,你必须覆盖GetHashCodeEquals如果你想使用你的类作为Dictionary的关键,否则你会比较参考。

下面是一个例子,其中Equals检查两个项目是否具有相同的Name

public class Item 
{ 
    public override int GetHashCode() 
    { 
     return Name == null ? 0 : Name.GetHashCode(); 
    } 

    public override bool Equals(object obj) 
    { 
     if (obj == null) return false; 
     if(object.ReferenceEquals(this, obj)) return true; 
     Item i2 = obj as Item; 
     if(i2 == null) return false; 
     return StringComparer.CurrentCulture.Equals(Name, i2.Name); 
    } 
    // rest of class ... 
} 

但问题不明确。您可以使用字典按键查找元素。所以你想通过提供密钥来找到价值。这意味着你已经有了一个让你的问题毫无意义的关键。

但是,您可以循环,即使它不是这个做了一个解释:

foreach(var kv in mydictronary) 
{ 
    Item i = kv.Key; 
    // now you have all properties of it 
} 
1

要检索您的项目,您需要使用相同的项目(相同的参考)。你可以做到这一点在这样的方式:

var myDouble = myDictonary[item]; 

当您使用对象为在目录中的关键,它的散列码是使用添加/从中检索项目 - 你可以阅读更多here

如果您要使用字符串来检索项目,那么你应该使用字符串作为你的一个关键词典:

Dictonary<string,double> mydictronary = new Dictonary<string,double>(); 
+0

这会找回他的价值是双倍的 – Tal87

+0

嗯,那么可能我不明白这个问题。 –

+0

据我所知,mr.energy希望使用字典的关键字的属性,而不是价值 – Tal87

0

你可以这样迭代词典:

foreach(var keyValuePair in myDictionary) { kvp.Key. }

然后你会得到所有的属性

0

您可以使用LINQ的:

var item = myDictionary.Where(x => x.Key.Name == "myItem"); 
var item = myDictionary.Where(x => x.Key.Sku == 123); 
0

你有三个选择。

  1. 您可以使用该类的同一个实例进行索引,如var x = myDictionary[item]
  2. 您可以实现一个客户比较器(实现IEqualityComparer<Item>),并将其传递给您的字典的构造函数。详情请参阅MSDN
  3. 你可以在你的Item类上实现IEquatable<Item>。详情请参阅IEquatable on MSDN
0

您可以从Dictionary<TKey, TValue>.Keys属性中访问密钥。

从MSDN

// To get the keys alone, use the Keys property. 
Dictionary<string, string>.KeyCollection keyColl = openWith.Keys; 

// The elements of the KeyCollection are strongly typed 
// with the type that was specified for dictionary keys. 
Console.WriteLine(); 
foreach(string s in keyColl) 
{ 
    Console.WriteLine("Key = {0}", s); 
}