IEqualityComparer and singleton

三世轮回 提交于 2019-12-10 13:30:31

问题


I was wondering if there is possibility to use singleton as comparerObject in for example 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 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() )  );

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 ??


回答1:


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
}

Then:

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.)



来源:https://stackoverflow.com/questions/5640071/iequalitycomparer-and-singleton

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!