【发布时间】:2013-05-20 09:03:40
【问题描述】:
我有一个保存更改列表的网页,因此在保存操作中我有两个列表,一个包含新值,一个包含现有值。
我想:
- 遍历两个列表,合并和重复数据删除。
- 我想在新列表而不是现有列表的哪个位置添加新项目。
- 我想在两个列表中的哪个位置跳过它。
- 我想在现有列表中但不在新列表中的哪个位置删除该项目。
敲出一个方法来做到这一点很容易,比如:
public static IEnumerable<UnionCompared<T>> UnionCompare<T>(
this IEnumerable<T> first, IEnumerable<T> compare, IEqualityComparer<T> comparer = null)
{
// Create hash sets to check which collection the element is in
var f = new HashSet<T>(first, comparer);
var s = new HashSet<T>(compare, comparer);
// Use Union as it dedupes
var combined = first.Union(compare, comparer);
foreach (var c in combined)
{
// Create a type that has the item and a flag for which collection it's in
var retval = new UnionCompared<T>
{
Item = c,
InFirst = f.Contains(c),
InCompare = s.Contains(c)
};
yield return retval;
}
}
但是,这更像是重新发明轮子。有什么东西已经这样做了吗?这似乎是其他人已经解决的问题。
有没有更好的办法?
【问题讨论】:
标签: .net extension-methods ienumerable