我有兩個詞典,如:比較兩個列表<enum>對象在C#中
Dictionary<string, object> dict1 = new Dictionary<string, object>();
Dictionary<string, object> dict2 = new Dictionary<string, object>();
我想對它們進行比較,其中一些條目List<Enum>
,我怎麼能比較這些List<Enum>
對象。請看下面的示例代碼:
enum Days { Monday, Tuesday, Wednesday }
enum Colors { Red, Green, Blue }
enum Cars { Acura, BMW, Ford }
填充字典:
List<Days> lst1 = new List<Days>();
List<Days> lst2 = new List<Days>();
lst1.Add(Days.Monday); lst1.Add(Days.Tuesday);
lst2.Add(Days.Monday); lst2.Add(Days.Tuesday);
dict1.Add("DayEnum", lst1);
dict2.Add("DayEnum", lst2);
foreach (KeyValuePair<string, object> entry in dict1)
{
var t1 = dict1[entry.Key];
var t2 = dict2[entry.Key];
if (dict1[entry.Key].GetType().IsGenericType && Compare(dict1[entry.Key], dict2[entry.Key]))
{
// List elements matches...
}
else if (dict1[entry.Key].Equals(dict2[entry.Key]))
{
// Other elements matches...
}
}
不匹配,除非我提供確切的枚舉即IEnumerable<Days>
,但我需要一個通用的代碼,以用於任何枚舉工作。
到目前爲止,我發現下面的方式來比較,但我需要一個通用的比較語句,我不知道所有的枚舉:
private static bool Compare<T>(T t1, T t2)
{
if (t1 is IEnumerable<T>)
{
return (t1 as IEnumerable<T>).SequenceEqual(t2 as IEnumerable<T>);
}
else
{
Type[] genericTypes = t1.GetType().GetGenericArguments();
if (genericTypes.Length > 0 && genericTypes[0].IsEnum)
{
if (genericTypes[0] == typeof(Days))
{
return (t1 as IEnumerable<Days>).SequenceEqual(t2 as IEnumerable<Days>);
}
else if (genericTypes[0] == typeof(Colors))
{
return (t1 as IEnumerable<Colors>).SequenceEqual(t2 as IEnumerable<Colors>);
}
}
return false;
}
}
爲什麼你需要測試它是否是特定的枚舉列表?枚舉是值類型,所以你可以測試值類型。 –
@大衛,它不是枚舉比較,它是枚舉比較列表,它不能像數值類型那樣進行比較。 – Asim
那肯定是列表比較問題? –