优化通用 AddDistinct 扩展方法
我可以更有效地编写这些函数吗?
public static void AddDistinct<T>(this ICollection<T> source, params ICollection<T>[] collections)
{
(from collection in collections from item in collection where !source.Contains(item) select item).ForEach(source.Add);
}
public static void AddDistinct<T>(this ICollection<T> source, Func<T, bool> predicate, params ICollection<T>[] collections)
{
collections.ForEach(collection => collection.Where(predicate).Where(item => !source.Contains(item)).ForEach(source.Add));
}
public static void AddDistinct<T>(this ICollection<T> source, params T[] items)
{
items.Where(item => !source.Contains(item)).ForEach(source.Add);
}
public static void AddDistinct<T>(this ICollection<T> source, Func<T, bool> predicate, params T[] items)
{
items.Where(predicate).Where(x => !source.Contains(x)).ForEach(source.Add);
}
Can I write these functions more efficient?
public static void AddDistinct<T>(this ICollection<T> source, params ICollection<T>[] collections)
{
(from collection in collections from item in collection where !source.Contains(item) select item).ForEach(source.Add);
}
public static void AddDistinct<T>(this ICollection<T> source, Func<T, bool> predicate, params ICollection<T>[] collections)
{
collections.ForEach(collection => collection.Where(predicate).Where(item => !source.Contains(item)).ForEach(source.Add));
}
public static void AddDistinct<T>(this ICollection<T> source, params T[] items)
{
items.Where(item => !source.Contains(item)).ForEach(source.Add);
}
public static void AddDistinct<T>(this ICollection<T> source, Func<T, bool> predicate, params T[] items)
{
items.Where(predicate).Where(x => !source.Contains(x)).ForEach(source.Add);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用
Except
方法:请注意,由于
Where
和Except
具有延迟和流式执行,因此您需要ToArray()< /code> 调用以确保在向其中添加任何内容之前完成
source
的枚举(因为在枚举集合时无法对其进行修改)。You can use the
Except
method:Note that because
Where
andExcept
have deferred and streamed execution, you need theToArray()
call to ensure the enumeration ofsource
is complete before you add anything to it (since a collection can't be modified while it's being enumerated).是的,使用例如哈希集,您可以比
O(N*M)
做得更好。Yes, using e.g. a hashset you can do much better than
O(N*M)
.我认为使用
HashSet
和IEnumerable
可以更高效。 HashSet 可以高效地跟踪重复项,您只需浏览一次源即可将它们加载到集合中。除非我弄错了,否则我认为ICollection
和T[]
都是IEnumerable
吗?但不确定您需要这些谓词版本做什么。您不能在添加项目之前过滤它们吗?
Using
HashSet<T>
andIEnumerable<T>
you can do it more efficient I think. The HashSet is efficient at keeping track of duplicates, and you only need to go through the source once to load them into the set. And unless I'm mistaken, I think bothICollection<T>
andT[]
areIEnumerable<T>
s?Not sure what you need those predicate versions for though. Can't you just filter your items before you add them?