我有以下课程
public class MyObject
{
public int Id1 {get;set;}
public int Id2 {get;set;}
public int Id3 {get;set;}
public MyObject(int id1, int id2, int id3)
{
this.Id1 = id1;
this.Id2 = id2;
this.Id3 = id3;
}
}
我想在Dictionary中创建一个对象列表。我最好这样做吗
Dictionary<MyObject, MyObject> dictionary = new Dictionary<MyObject,MyObject>();
MyObject object1 = new MyObject(1,2,3);
MyObject object2 = new MyObject(2,2,3);
MyObject object3 = new MyObject(2,2,3);
if(!dictionary.ContainsKey(object1))
dictionary.Add(object1,object1);
if(!dictionary.ContainsKey(object2))
dictionary.Add(object2,object2);
if(!dictionary.ContainsKey(object3))
dictionary.Add(object3,object3);
或者我应该创建一个字典,其中键是一个字符串,并包含连接的字符串。例如
Dictionary<string, MyObject> dictionary2 = new Dictionary<string,MyObject>();
string key = object1.Id1 + "|" + object1.Id2 + "|" + object1.Id3;
if(!dictionary2.ContainsKey(key ))
dictionary2.Add(key ,object1);
答案 0 :(得分:3)
Equals
或GetHashCode
+ MyObject
IEqualityComparer<MyObject>
传递给字典构造函数但将此对象存储为键和值是没有意义的。也许您想要使用HashSet<MyObject>
。
答案 1 :(得分:2)
看起来你想要的是一个Hashset,因为键和值是相同的,你不想要重复。
您需要这个类来告诉哪些对象是相同的。
class MyObjectEqualityComparer : IEqualityComparer<MyObject>
{
MyObjectEqualityComparer()
{
}
public static readonly MyObjectEqualityComparer Default = new MyObjectEqualityComparer();
public bool Equals(MyObject x, MyObject y)
{
return x.Id1 == y.Id1 && x.Id2 == y.Id2 && x.Id3 == y.Id3;
}
public int GetHashCode(MyObject obj)
{
return obj.Id1.GetHashCode() ^ obj.Id2.GetHashCode() ^ obj.Id3.GetHashCode();
}
}
然后制作一个哈希集
HashSet<MyObject> set = new HashSet<MyObject>(MyObjectEqualityComparer.Default);
MyObject object1 = new MyObject(1,2,3);
MyObject object2 = new MyObject(2,2,3);
MyObject object3 = new MyObject(2,2,3);
if(set.Add(object1))
{
// item was added.
}
else
{
// item already exist.
}