我有两个词典,如下所示:
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...
}
}
如果我不提供准确的Enum,例如 IEnumerable<Days>
,它就无法匹配,但我需要一种通用的代码来适用于任何Enum。
到目前为止,我找到了以下比较方式,但我需要一个通用的比较语句,因为我不知道所有的Enums:
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;
}
}