复合键字典 [英] Composite Key Dictionary

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

问题描述

我在列表一些对象,比方说列表< MyClass的> 和MyClass的有几个属性。我想创建的基础上的MyClass 3个属性列表中的索引。在这种情况下,属性2是INT的,和一个属性是一个日期时间

I have some objects in List, let's say List<MyClass> and MyClass has several properties. I would like to create an index of the list based on 3 properties of of MyClass. In this case 2 of the properties are int's, and one property is a datetime.

基本上我希望能够做这样的事情:

Basically I would like to be able to do something like:

Dictionary< CompositeKey , MyClass > MyClassListIndex = Dictionary< CompositeKey , MyClass >();
//Populate dictionary with items from the List<MyClass> MyClassList
MyClass aMyClass = Dicitonary[(keyTripletHere)];

我有时一个列表,其持有的类指数不同属性上创建多个字典。我不知道如何以最佳方式处理,虽然组合键。我认为做三个值的校验和,但这运行碰撞的风险。

I sometimes create multiple dictionaries on a list to index different properties of the classes it holds. I am not sure how best to handle composite keys though. I considered doing a checksum of the three values but this runs the risk of collisions.

推荐答案

您应该使用的元组。他们是相当于一个CompositeKey类,但equals()和GetHash code()已经为你实现。

You should use tuples. They are equivalent to a CompositeKey class, but the Equals() and GetHashCode() are already implemented for you.

var myClassIndex = new Dictionary<Tuple<int, bool, string>, MyClass>();
//Populate dictionary with items from the List<MyClass> MyClassList
foreach (var myObj in myClassList)
    myClassIndex.Add(Tuple.Create(myObj.MyInt, myObj.MyBool, myObj.MyString), myObj);
MyClass myObj = myClassIndex[Tuple.Create(4, true, "t")];

或使用System.Linq的

Or using System.Linq

var myClassIndex = myClassList.ToDictionary(myObj => Tuple.Create(myObj.MyInt, myObj.MyBool, myObj.MyString));
MyClass myObj = myClassIndex[Tuple.Create(4, true, "t")];

除非你需要定制散列计算,它更简单易用的元组。

Unless you need to customize the computation of the hash, it's more simple to use tuples.

如果有很多你想要的组合键,包括属性,元组类型名称可以成为pretty长,但可以使名义通过创建自己的类从元组LT衍生短; ... >。

If there are a lot of properties you want to include in the composite key, the Tuple type name can become pretty long, but you can make the name shorter by creating your own class deriving from Tuple<...>.

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆