到現在爲止我有2個字典的Dictionary<string, int>
類型,需要得到的所有內容在dict1
但不在dict2
使用except
。例如:使用除對象爲字典的字典
Dictionary<string, int> dict1 = new Dictionary<string, int>
{
{ "aaa", 1 },
{ "bbb", 2 }
};
Dictionary<string, int> dict2 = new Dictionary<string, int>
{
{ "aaa", 2 },
{ "bbb", 2 }
};
var newDict = dict1.Except(dict2);
newDict
現在包含{ 「AAA」,1}這是我所期望的,因爲價值是不同的。
我的問題是,我們需要字典中的附加值,因此我們將Dictionary<string, int>
更改爲Dictionary<string, MyObject>
。當我現在使用except
時,我沒有得到我想要的結果。例如:
public class MyObject
{
public MyObject(string name, int someNumber)
{
myString = name;
myInt = someNumber;
}
public string myString { get; set; }
public int myInt { get; set; }
}
class Program
{
static void Main(string[] args)
{
Dictionary<string, MyObject> dict1 = new Dictionary<string, MyObject>
{
{ "aaa", new MyObject("abc", 1) },
{ "bbb", new MyObject("def", 2) }
};
Dictionary<string, MyObject> dict2 = new Dictionary<string, MyObject>
{
{ "aaa", new MyObject("abc", 2) },
{ "bbb", new MyObject("def", 2) }
};
var newDict = dict1.Except(dict2);
}
}
newDict
現在包含dict1所有KVP,但其實我只希望有從dict1中的第一項。我認爲這是因爲MyObject的值沒有被比較。我能做些什麼來解決這個問題? Linq有沒有簡單的方法?
在此先感謝!
'KeyValuePair'使用['ValueType.Equals'](https://msdn.microsoft.com/en-us/library/2dts52z7(v = vs.110).aspx)來比較兩個字典項目。如果'TKey'和'TValue'是值類型,那麼這是有效的。如果兩者中的一個都是引用類型,則兩者必須是相同的引用,否則'Equals'返回'false'。既然你有兩個不同的實例('new MyObject ...'),它們是不相等的。 –
覆蓋'MyObject'中的'Equals' +'GetHashCode' –