今天我正在使用ConcurrentDictionary和Dictionary进行一些测试:
class MyTest
{
public int Row { get; private set; }
public int Col { get; private set; }
public string Value { get; private set; }
public MyTest(int row, int col, string value)
{
this.Col = col;
this.Row = row;
this.Value = value;
}
public override bool Equals(object obj)
{
MyTest other = obj as MyTest;
return base.Equals(other);
}
public override int GetHashCode()
{
return (Col.GetHashCode() ^ Row.GetHashCode() ^ Value.GetHashCode());
}
}
使用上面的Entity我创建并填充了ConcurrentDictionary和Dictionary并尝试了下面的代码:
ConcurrentDictionary<MyTest, List<MyTest>> _test = new ConcurrentDictionary<MyTest, List<MyTest>>();
Dictionary<MyTest, List<MyTest>> _test2 = new Dictionary<MyTest, List<MyTest>>();
MyTest dunno = _test.Values.AsParallel().Select(x => x.Find(a => a.Col == 1 && a.Row == 1)).FirstOrDefault();
MyTest dunno2 = _test2.Values.AsParallel().Select(x => x.Find(a => a.Col == 1 && a.Row == 1)).FirstOrDefault();
第一个返回值,但第二个不返回,我做错了什么?
这是用于添加值的代码:
_test.AddOrUpdate(cell10,
new List<MyTest>
{
new MyTest(1, 1, "ovpSOMEVALUEValue"),
new MyTest(1, 2, "ocpSOMEVALUEValue")
},
(key, value) => value = new List<MyTest>());
_test2.Add(cell10,
new List<MyTest>
{
new MyTest(1, 1, "ovpSOMEVALUEValue"),
new MyTest(1, 2, "ocpSOMEVALUEValue")
}
);
答案 0 :(得分:3)
您正在调用Equals
,而您的第三个参数是它应该创建一个新的空列表,因此结果是您最终得到一个空列表。我猜这个代码行之前的某个地方你正在添加一个具有相同密钥的条目。
另请注意GetHashCode
功能不正确。您正在比较参考,而不是您在 protected bool Equals(x other) {
return Row == other.Row && Col == other.Col && string.Equals(Value, other.Value);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != this.GetType()) return false;
return Equals((x) obj);
}
public override int GetHashCode()
{
unchecked
{
var hashCode = Row;
hashCode = (hashCode*397) ^ Col;
hashCode = (hashCode*397) ^ (Value != null ? Value.GetHashCode() : 0);
return hashCode;
}
}
中使用的实际值。我建议你使用默认模板来覆盖Equals:
#include <stdio.h>
#include <stdlib.h>
/* t's value in ASCII */
#define LETTER_T 116
int main(int argc, char * argv[])
{
/* Use toupper or tolower functions to handle casing */
char * str = "brad";
char * result = (str[0] < LETTER_T) ? "before" : "after";
printf("%s starts with a %c that comes %s the letter t.", str, str[0], result);
return 0;
}