从 C# 中的 List<T> 中删除重复项
-
09-06-2019 - |
题
有人有一种在 C# 中对通用列表进行重复数据删除的快速方法吗?
解决方案
也许你应该考虑使用 哈希集.
来自 MSDN 链接:
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
HashSet<int> evenNumbers = new HashSet<int>();
HashSet<int> oddNumbers = new HashSet<int>();
for (int i = 0; i < 5; i++)
{
// Populate numbers with just even numbers.
evenNumbers.Add(i * 2);
// Populate oddNumbers with just odd numbers.
oddNumbers.Add((i * 2) + 1);
}
Console.Write("evenNumbers contains {0} elements: ", evenNumbers.Count);
DisplaySet(evenNumbers);
Console.Write("oddNumbers contains {0} elements: ", oddNumbers.Count);
DisplaySet(oddNumbers);
// Create a new HashSet populated with even numbers.
HashSet<int> numbers = new HashSet<int>(evenNumbers);
Console.WriteLine("numbers UnionWith oddNumbers...");
numbers.UnionWith(oddNumbers);
Console.Write("numbers contains {0} elements: ", numbers.Count);
DisplaySet(numbers);
}
private static void DisplaySet(HashSet<int> set)
{
Console.Write("{");
foreach (int i in set)
{
Console.Write(" {0}", i);
}
Console.WriteLine(" }");
}
}
/* This example produces output similar to the following:
* evenNumbers contains 5 elements: { 0 2 4 6 8 }
* oddNumbers contains 5 elements: { 1 3 5 7 9 }
* numbers UnionWith oddNumbers...
* numbers contains 10 elements: { 0 2 4 6 8 1 3 5 7 9 }
*/
其他提示
如果您使用 .Net 3+,则可以使用 Linq。
List<T> withDupes = LoadSomeData();
List<T> noDupes = withDupes.Distinct().ToList();
怎么样:-
var noDupes = list.Distinct().ToList();
在.net 3.5 中?
只需使用相同类型的 List 初始化 HashSet:
var noDupes = new HashSet<T>(withDupes);
或者,如果您想要返回列表:
var noDupsList = new HashSet<T>(withDupes).ToList();
将其排序,然后检查两个和两个相邻的,因为重复项会聚集在一起。
像这样的东西:
list.Sort();
Int32 index = list.Count - 1;
while (index > 0)
{
if (list[index] == list[index - 1])
{
if (index < list.Count - 1)
(list[index], list[list.Count - 1]) = (list[list.Count - 1], list[index]);
list.RemoveAt(list.Count - 1);
index--;
}
else
index--;
}
笔记:
- 比较是从后到前进行的,以避免每次删除后都必须重新排序列表
- 此示例现在使用 C# 值元组进行交换,如果您无法使用该代码,请替换为适当的代码
- 最终结果不再排序
这对我有用。只需使用
List<Type> liIDs = liIDs.Distinct().ToList<Type>();
将“类型”替换为您想要的类型,例如国际。
我喜欢使用这个命令:
List<Store> myStoreList = Service.GetStoreListbyProvince(provinceId)
.GroupBy(s => s.City)
.Select(grp => grp.FirstOrDefault())
.OrderBy(s => s.City)
.ToList();
我的列表中有这些字段:ID,StoreName,City,邮政编码我想在一个具有重复值的下拉列表中显示城市列表。解决方案:按城市分组,然后选择列表中的第一个。
我希望它有帮助:)
正如 kronoz 在 .Net 3.5 中所说,你可以使用 Distinct()
.
在 .Net 2 中你可以模仿它:
public IEnumerable<T> DedupCollection<T> (IEnumerable<T> input)
{
var passedValues = new HashSet<T>();
// Relatively simple dupe check alg used as example
foreach(T item in input)
if(passedValues.Add(item)) // True if item is new
yield return item;
}
这可用于对任何集合进行重复数据删除,并按原始顺序返回值。
通常过滤集合要快得多(因为 Distinct()
这个示例确实如此)而不是从中删除项目。
扩展方法可能是一个不错的方法......像这样的东西:
public static List<T> Deduplicate<T>(this List<T> listToDeduplicate)
{
return listToDeduplicate.Distinct().ToList();
}
然后像这样调用,例如:
List<int> myFilteredList = unfilteredList.Deduplicate();
在 Java 中(我假设 C# 或多或少相同):
list = new ArrayList<T>(new HashSet<T>(list))
如果你真的想改变原始列表:
List<T> noDupes = new ArrayList<T>(new HashSet<T>(list));
list.clear();
list.addAll(noDupes);
要保持顺序,只需将 HashSet 替换为 LinkedHashSet 即可。
使用 Linq 的 联盟 方法。
笔记:除了 Linq 存在以外,该解决方案不需要任何有关 Linq 的知识。
代码
首先将以下内容添加到类文件的顶部:
using System.Linq;
现在,您可以使用以下命令从名为的对象中删除重复项, obj1
:
obj1 = obj1.Union(obj1).ToList();
笔记:改名 obj1
到你的对象的名称。
怎么运行的
Union 命令列出两个源对象的每个条目之一。由于 obj1 都是源对象,因此这会将 obj1 减少为每个条目之一。
这
ToList()
返回一个新列表。这是必要的,因为 Linq 命令如下Union
将结果作为 IEnumerable 结果返回,而不是修改原始 List 或返回新 List。
如果你不关心顺序,你可以将物品推入一个 HashSet
, , 如果你 做 想要维持顺序,你可以这样做:
var unique = new List<T>();
var hs = new HashSet<T>();
foreach (T t in list)
if (hs.Add(t))
unique.Add(t);
或者 Linq 方式:
var hs = new HashSet<T>();
list.All( x => hs.Add(x) );
编辑: 这 HashSet
方法是 O(N)
时间和 O(N)
排序时留出空间,然后使其唯一(按照@的建议)拉塞夫克 和其他)是 O(N*lgN)
时间和 O(1)
空间,所以我不太清楚(乍一看)排序方式较差(我对暂时的否决表示歉意......)
这是一种用于原位删除相邻重复项的扩展方法。首先调用 Sort() 并传入相同的 IComparer。这应该比 Lasse V 更有效。Karlsen 的版本重复调用RemoveAt(导致多次块内存移动)。
public static void RemoveAdjacentDuplicates<T>(this List<T> List, IComparer<T> Comparer)
{
int NumUnique = 0;
for (int i = 0; i < List.Count; i++)
if ((i == 0) || (Comparer.Compare(List[NumUnique - 1], List[i]) != 0))
List[NumUnique++] = List[i];
List.RemoveRange(NumUnique, List.Count - NumUnique);
}
作为辅助方法(不使用 Linq):
public static List<T> Distinct<T>(this List<T> list)
{
return (new HashSet<T>(list)).ToList();
}
安装 更多LINQ 通过Nuget打包,您可以轻松地通过属性区分对象列表
IEnumerable<Catalogue> distinctCatalogues = catalogues.DistinctBy(c => c.CatalogueCode);
这需要不同的(没有重复元素的元素)并将其再次转换为列表:
List<type> myNoneDuplicateValue = listValueWithDuplicate.Distinct().ToList();
只需确保不将重复项添加到列表中可能会更容易。
if(items.IndexOf(new_item) < 0)
items.add(new_item)
.Net 2.0 中的另一种方式
static void Main(string[] args)
{
List<string> alpha = new List<string>();
for(char a = 'a'; a <= 'd'; a++)
{
alpha.Add(a.ToString());
alpha.Add(a.ToString());
}
Console.WriteLine("Data :");
alpha.ForEach(delegate(string t) { Console.WriteLine(t); });
alpha.ForEach(delegate (string v)
{
if (alpha.FindAll(delegate(string t) { return t == v; }).Count > 1)
alpha.Remove(v);
});
Console.WriteLine("Unique Result :");
alpha.ForEach(delegate(string t) { Console.WriteLine(t);});
Console.ReadKey();
}
有很多方法可以解决列表中的重复问题,以下是其中之一:
List<Container> containerList = LoadContainer();//Assume it has duplicates
List<Container> filteredList = new List<Container>();
foreach (var container in containerList)
{
Container duplicateContainer = containerList.Find(delegate(Container checkContainer)
{ return (checkContainer.UniqueId == container.UniqueId); });
//Assume 'UniqueId' is the property of the Container class on which u r making a search
if(!containerList.Contains(duplicateContainer) //Add object when not found in the new class object
{
filteredList.Add(container);
}
}
欢呼拉维·甘尼森(Ravi Ganesan)
这是一个简单的解决方案,不需要任何难以阅读的 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
}
}
}
}
David J.的回答是一个很好的方法,不需要额外的对象、排序等。但它还可以改进:
for (int innerIndex = items.Count - 1; innerIndex > outerIndex ; innerIndex--)
因此,外部循环在整个列表中从上到下,但内部循环从底部“直到到达外循环位置”。
外部循环确保处理整个列表,内部循环查找实际的重复项,这些重复项只能发生在外部循环尚未处理的部分中。
或者,如果您不想对内部循环进行自下而上的操作,则可以让内部循环从outerIndex + 1 开始。
您可以使用联盟
obj2 = obj1.Union(obj1).ToList();
如果你有两节课 Product
和 Customer
我们想从列表中删除重复的项目
public class Product
{
public int Id { get; set; }
public string ProductName { get; set; }
}
public class Customer
{
public int Id { get; set; }
public string CustomerName { get; set; }
}
您必须按下面的形式定义一个泛型类
public class ItemEqualityComparer<T> : IEqualityComparer<T> where T : class
{
private readonly PropertyInfo _propertyInfo;
public ItemEqualityComparer(string keyItem)
{
_propertyInfo = typeof(T).GetProperty(keyItem, BindingFlags.GetProperty | BindingFlags.Instance | BindingFlags.Public);
}
public bool Equals(T x, T y)
{
var xValue = _propertyInfo?.GetValue(x, null);
var yValue = _propertyInfo?.GetValue(y, null);
return xValue != null && yValue != null && xValue.Equals(yValue);
}
public int GetHashCode(T obj)
{
var propertyValue = _propertyInfo.GetValue(obj, null);
return propertyValue == null ? 0 : propertyValue.GetHashCode();
}
}
然后,您可以删除列表中的重复项目。
var products = new List<Product>
{
new Product{ProductName = "product 1" ,Id = 1,},
new Product{ProductName = "product 2" ,Id = 2,},
new Product{ProductName = "product 2" ,Id = 4,},
new Product{ProductName = "product 2" ,Id = 4,},
};
var productList = products.Distinct(new ItemEqualityComparer<Product>(nameof(Product.Id))).ToList();
var customers = new List<Customer>
{
new Customer{CustomerName = "Customer 1" ,Id = 5,},
new Customer{CustomerName = "Customer 2" ,Id = 5,},
new Customer{CustomerName = "Customer 2" ,Id = 5,},
new Customer{CustomerName = "Customer 2" ,Id = 5,},
};
var customerList = customers.Distinct(new ItemEqualityComparer<Customer>(nameof(Customer.Id))).ToList();
此代码删除重复的项目 Id
如果您想通过其他属性删除重复的项目,您可以更改 nameof(YourClass.DuplicateProperty)
相同的 nameof(Customer.CustomerName)
然后删除重复的项目 CustomerName
财产。
public static void RemoveDuplicates<T>(IList<T> list )
{
if (list == null)
{
return;
}
int i = 1;
while(i<list.Count)
{
int j = 0;
bool remove = false;
while (j < i && !remove)
{
if (list[i].Equals(list[j]))
{
remove = true;
}
j++;
}
if (remove)
{
list.RemoveAt(i);
}
else
{
i++;
}
}
}
一个简单直观的实现:
public static List<PointF> RemoveDuplicates(List<PointF> listPoints)
{
List<PointF> result = new List<PointF>();
for (int i = 0; i < listPoints.Count; i++)
{
if (!result.Contains(listPoints[i]))
result.Add(listPoints[i]);
}
return result;
}
所有答案都会复制列表,或者创建一个新列表,或者使用缓慢的函数,或者只是慢得令人痛苦。
据我了解,这就是 最快且最便宜的方法 我知道(而且有一位非常有经验的专门从事实时物理优化的程序员的支持)。
// Duplicates will be noticed after a sort O(nLogn)
list.Sort();
// Store the current and last items. Current item declaration is not really needed, and probably optimized by the compiler, but in case it's not...
int lastItem = -1;
int currItem = -1;
int size = list.Count;
// Store the index pointing to the last item we want to keep in the list
int last = size - 1;
// Travel the items from last to first O(n)
for (int i = last; i >= 0; --i)
{
currItem = list[i];
// If this item was the same as the previous one, we don't want it
if (currItem == lastItem)
{
// Overwrite last in current place. It is a swap but we don't need the last
list[i] = list[last];
// Reduce the last index, we don't want that one anymore
last--;
}
// A new item, we store it and continue
else
lastItem = currItem;
}
// We now have an unsorted list with the duplicates at the end.
// Remove the last items just once
list.RemoveRange(last + 1, size - last - 1);
// Sort again O(n logn)
list.Sort();
最终成本为:
nlogn + n + nlogn = n + 2nlogn = O(nlogn) 这非常好。
关于删除范围的注意事项:由于我们无法设置列表的计数并避免使用删除函数,因此我不知道此操作的确切速度,但我想这是最快的方法。