谁有一个快速的方法去重复在c#的泛型列表?


当前回答

通过Nuget安装MoreLINQ包,你可以很容易地通过属性区分对象列表

IEnumerable<Catalogue> distinctCatalogues = catalogues.DistinctBy(c => c.CatalogueCode); 

其他回答

这里有一个简单的解决方案,不需要任何难读的LINQ或任何列表的预先排序。

   private static void CheckForDuplicateItems(List<string> items)
    {
        if (items == null ||
            items.Count == 0)
            return;

        for (int outerIndex = 0; outerIndex < items.Count; outerIndex++)
        {
            for (int innerIndex = 0; innerIndex < items.Count; innerIndex++)
            {
                if (innerIndex == outerIndex) continue;
                if (items[outerIndex].Equals(items[innerIndex]))
                {
                    // Duplicate Found
                }
            }
        }
    }

作为一个辅助方法(没有Linq):

public static List<T> Distinct<T>(this List<T> list)
{
    return (new HashSet<T>(list)).ToList();
}

通过Nuget安装MoreLINQ包,你可以很容易地通过属性区分对象列表

IEnumerable<Catalogue> distinctCatalogues = catalogues.DistinctBy(c => c.CatalogueCode); 

简单地用相同类型的List初始化HashSet:

var noDupes = new HashSet<T>(withDupes);

或者,如果你想返回一个List:

var noDupsList = new HashSet<T>(withDupes).ToList();

使用Linq的Union方法。

注意:这个解决方案不需要了解Linq,只需要知道它存在。

Code

首先将以下内容添加到类文件的顶部:

using System.Linq;

现在,你可以使用下面的方法从一个名为obj1的对象中删除重复项:

obj1 = obj1.Union(obj1).ToList();

注意:将obj1重命名为对象的名称。

它是如何工作的

Union命令列出两个源对象的每个条目中的一个。由于obj1都是源对象,这将把obj1减少为每个条目中的一个。 ToList()返回一个新的List。这是必要的,因为像Union这样的Linq命令将结果返回为IEnumerable结果,而不是修改原来的List或返回一个新的List。