我有一个函数,它返回一个List<Dictionary<string, object>>where对象是标准类型(string,int等).
我需要花一点时间List<Dictionary<string, object>>并确保列表B中的所有条目都在列表A中表示(列表中的顺序无关紧要).
目前我的代码如下所示:
foreach(Dictionary<string, object> rowResult in A) {
foreach(Dictionary<string, object> rowCompare in B) {
foreach(string columnName in rowResult.Keys) {
// ... logic to compare columns
}
}
// ...logic to compare rows so we dont find the same row twice.
}
Run Code Online (Sandbox Code Playgroud)
有没有更简单的方法来做到这一点?
我们不在乎找到rowResult中的所有行,但rowCompare中的所有行都必须是.它是确定以删除行比较或结果集进行迭代更加容易.
我的代码工作,它只是看起来复杂和脆弱.
class DictionaryComparer<TKey, TValue> : IEqualityComparer<Dictionary<TKey, TValue>> {
public bool Equals(Dictionary<TKey, TValue> x, Dictionary<TKey, TValue> y) {
if (x == null) {
throw new ArgumentNullException("x");
}
if (y == null) {
throw new ArgumentNullException("y");
}
if (x.Count != y.Count) {
return false;
}
foreach (var kvp in x) {
TValue value;
if(!y.TryGetValue(kvp.Key, out value)) {
return false;
}
if(!kvp.Value.Equals(value)) {
return false;
}
}
return true;
}
public int GetHashCode(Dictionary<TKey, TValue> obj) {
if (obj == null) {
throw new ArgumentNullException("obj");
}
int hash = 0;
foreach (var kvp in obj) {
hash = hash ^ kvp.Key.GetHashCode() ^ kvp.Value.GetHashCode();
}
return hash;
}
}
Run Code Online (Sandbox Code Playgroud)
然后:
public bool Contains(
List<Dictionary<string, object>> first,
List<Dictionary<string, object>> second) {
if(first == null) {
throw new ArgumentNullException("first");
}
if(second == null) {
throw new ArgumentNullException("second");
}
IEqualityComparer<Dictionary<string, object>> comparer = new DictionaryComparer<string, object>();
return second.All(y => first.Contains(y, comparer));
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3038 次 |
| 最近记录: |