C# 字典中复杂键的数据结构
对于键复杂的字典(值的组合) 例如,密钥可以是一对字符串和整数 您建议对密钥使用哪种数据类型?我考虑了性能和内存使用情况,如果从字典中大量读取数据,那么分配繁重的数据类型可能不适合该任务 我测试了4种不同的策略C# 字典中复杂键的数据结构,c#,.net,dictionary,tuples,C#,.net,Dictionary,Tuples,对于键复杂的字典(值的组合) 例如,密钥可以是一对字符串和整数 您建议对密钥使用哪种数据类型?我考虑了性能和内存使用情况,如果从字典中大量读取数据,那么分配繁重的数据类型可能不适合该任务 我测试了4种不同的策略 最简单的一种,使用字符串作为键,并对组件进行编码: int Read(string str, int num) { var key = str + "|" + num; return dict[key]; } 使用元组表示密钥: int Read(string str
int Read(string str, int num)
{
var key = str + "|" + num;
return dict[key];
}
int Read(string str, int num)
{
var key = new Tuple<string, int>(str, num);
return dict[key];
}
int Read(string str, int num)
{
var key = new KeyValuePair<string, int>(str, num);
return dict[key];
}
int读取(字符串str,int num)
{
var key=新元组(str,num);
返回dict[键];
}
int Read(string str, int num)
{
var key = new Tuple<string, int>(str, num);
return dict[key];
}
int Read(string str, int num)
{
var key = new KeyValuePair<string, int>(str, num);
return dict[key];
}
int读取(字符串str,int num)
{
var key=新的KeyValuePair(str,num);
返回dict[键];
}
struct-KVPair
{
公钥{get;set;}
公共V值{get;set;}
公共KVPair(K键,V值)
{
钥匙=钥匙;
价值=价值;
}
公共覆盖布尔等于(对象对象对象)
{
如果(!(obj是KVPair))
{
返回false;
}
KVPair other=(KVPair)obj;
return Key.Equals(其他.Key)&&
Value.Equals(其他值);
}
公共覆盖int GetHashCode()
{
int keyHash=Key.GetHashCode();
int valHash=Value.GetHashCode();
return(((keyHash我更喜欢将特定类型与相关属性名一起使用:
public class RowKey
{
public string Title { get; set; }
public int Id { get; set; }
public RowKey()
{
}
public RowKey(string title, int id)
{
Title = title;
Id = id;
}
public override bool Equals(object obj)
{
if (!(obj is RowKey))
return false;
RowKey other = obj as RowKey;
return Title.Equals(other.Title) && Id.Equals(other.Id);
}
public override int GetHashCode()
{
int titleHash = Title.GetHashCode();
int idHash = Id.GetHashCode();
return (((titleHash << 5) + titleHash) ^ idHash);
}
}
但这和使用元组不一样吗?它是一个类,我反对它的考虑因素是分配。是的,但是,想想你的代码结构和组织。元组是通用的,你可能会失去你的上下文…在这种情况下,这是反对使用元组的一个很好的观点。但是让你的键成为一个结构而不是类呢?对于你的用例,c类要想跑得最快,请参见:
int Read(string str, int num)
{
var key = new RowKey(str, num);
return dict[key];
}