字典中的自定义键

字典中的自定义键

本文介绍了字典中的自定义键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,



我有一个以此产品类为密钥的字典。





private Dictionary< Product,long> _dictProduct = null;



publi class产品

{

$
  public string ProductName {get;组; }
  public string ProductCategory {get;组; }


}



public void MyMethod(string productName,string productCategory)

{

//

$
}



在这种方法中,我需要能够根据productName和productCategory从字典中检索相应的值。

如何实现这一目标?

Hello,

I've a dictionary with this Product class as key.


private Dictionary<Product, long> _dictProduct = null;

publi class Product
{

 public string ProductName { get; set; }
 public string ProductCategory { get; set; }

}

public void MyMethod(string productName, string productCategory)
{
//

}

In this method, I need to be able to retrieve the corresponding value from the dictionary based on productName and productCategory.
How do I achieve this please?

我是否需要制作在这里使用元组?

谢谢。

Do I need to make use of Tuple here?
Thanks.








推荐答案

var product1 = new Product() { ProductName = "A",
ProductCategory = "1" };

var product2 = new Product() { ProductName = "B", ProductCategory = 2" };


_dictProduct[product1] = 1;
_dictProduct[product2] = 2;

//Now if you try this
var product = new Product() { ProductName = "A", ProductCategory = "1" };

//Not found
var id = _dictProduct[product];

引用类型(字符串和其他非常特殊格式的类型除外)并不是真正设计为键。因此,在您按名称和类别查找产品的示例中,您将无法进行字典提供的常量时间查找。
您将拥有的唯一选项是枚举整个键列表。列表<产品>会有相同的行为,并会以你想要的方式工作。

Reference types (other than strings and other very specially formatted types) are not really designed to be keys. So in your example of finding a product by name and category, you aren't going to be able to do the constant time lookup that a dictionary provides. The only option you'll have is to enumerate the entire list of keys. A List<Product> would have the same behavior and would work the way you want.

所以,在你的例子中,我只使用List< Product>与LINQ结合使用。如果您确实需要将这两个值组合成一个复合键,那么创建一个简单的结构(而不​​是类)并在那里设置它们。然后实现IEquatable< T>,Object.Equals,
C#相等运算符,GetHashCode等,以正确实现struct的相等性。请注意,您的结构必须是不可变的,因为您的相等逻辑必须将它们两者合并为一个哈希值,并且哈希值在
对象的生命周期内不能更改。如果确实如此,那么你将无法再找到它。

So, in your example, I'd just use List<Product> in combination with LINQ. If you really need to combine these 2 values into a composite key then create a simple struct (not class) and set them there. Then implement IEquatable<T>, Object.Equals, the C# equality operators, GetHashCode, etc to properly implement equality on the struct. Note that your struct must be immutable because your equality logic has to combine both of them into a hash value and the hash value cannot change for the life of the object. If it does then you won't be able to find it again.


这篇关于字典中的自定义键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 10:24