的IEqualityComparer和单 [英] IEqualityComparer and singleton
问题描述
我想知道是否有可能使用singleton作为comparerObject在例如Distinct ??
I was wondering if there is possibility to use singleton as comparerObject in for example Distinct ??
让我们假设我有一个元素列表,我需要使用distinct函数。通常我会这样做
Let's say that I have a list of element and I need to use distinct function on that list. Normally I would do that this way
var result = list.Distinct(new ListElementComparer);
ListElementComparer是一个实现IEqualityComparer接口的类。
然而,让我们假设我将经常使用上面提到的代码,例如这样。
ListElementComparer is a class which implements IEqualityComparer interface. However let's assume that I will be using code mentioned above quite frequently for example that way .
List<List<Element>> elementList = new List<List<Elements>>();
List<List<Element>> resultList new List<List<Element>>();
foreach(var element in elementList )
resultList.AddRange(element.Distinct(new ListElementComparer() ) );
因此您可以创建ListElementComparer的对象很多次。在这种情况下有什么点使用singletone insted在每次迭代中创建ListElementComparer?如果我使用singleton,distinct方法会工作
So as You can object of ListElementComparer might be created quite a lot of times. In this case is there any point of using singletone insted of createing ListElementComparer in each iteration ? Will the distinct method work if I use singleton ??
推荐答案
是的,绝对,它将与单例: p>
Yes, absolutely, it will work fine with a singleton:
public class ListElementComparer : IEqualityComparer<List<Element>>
{
public static ListElementComparer Instance { get { return instance; } }
private static readonly ListElementComparer instance =
new ListElementComparer();
private ListElementComparer() {}
// Implement IEqualityComparer<List<Element>> here
}
然后:
resultList.AddRange(element.Distinct(ListElementComparer.Instance);
请注意,您的整个循环可以避免一些:
Note that your whole loop can be avoided somewhat:
var resultList = elementList
.SelectMany(x => x.Distinct(ListElementComparer.Instance))
.ToList();
这不适用于原来声明的类型,因为你的示例代码不工作,但是类似的东西。)
(This doesn't quite work with the originally-declared types, because your sample code doesn't quite work either... but something similar would.)
这篇关于的IEqualityComparer和单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!