的IEqualityComparer和单 [英] IEqualityComparer and singleton

查看:120
本文介绍了的IEqualityComparer和单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有可能使用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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆