您无法避免在 List 中出现重复。没办法 - 没有项目验证。
如果您不关心物品的顺序,请使用HashSet。
如果您想保留项目的顺序(实际上有一点歧义 - 项目应该出现在第一次添加的索引还是最后一次添加的索引)。但是您想确保所有项目都是唯一的,那么您应该编写自己的 List 类。 IE。实现IList<T>接口的东西:
public class ListWithoutDuplicates<T> : IList<T>
你在这里有不同的选择。例如。你应该决定什么对你更重要 - 快速添加或内存消耗。因为为了快速添加和包含操作,您应该使用一些基于哈希的数据结构。这是无序的。这是 HashSet 的示例实现,用于存储存储在内部列表中的所有项目的哈希值。您将需要以下字段:
private readonly HashSet<int> hashes = new HashSet<int>();
private readonly List<T> items = new List<T>();
private static readonly Comparer<T> comparer = Comparer<T>.Default;
添加项目很简单(警告:此处和其他地方没有空检查) - 使用项目哈希码快速 O(1) 检查它是否已添加。使用相同的方法删除项目:
public void Add(T item)
{
var hash = item.GetHashCode();
if (hashes.Contains(hash))
return;
hashes.Add(hash);
items.Add(item);
}
public bool Remove(T item)
{
var hash = item.GetHashCode();
if (!hashes.Contains(hash))
return false;
hashes.Remove(item.GetHashCode());
return items.Remove(item);
}
一些基于索引的操作:
public int IndexOf(T item)
{
var hash = item.GetHashCode();
if (!hashes.Contains(hash))
return -1;
return items.IndexOf(item);
}
public void Insert(int index, T item)
{
var itemAtIndex = items[index];
if (comparer.Compare(item, itemAtIndex) == 0)
return;
var hash = item.GetHashCode();
if (!hashes.Contains(hash))
{
hashes.Remove(itemAtIndex.GetHashCode());
items[index] = item;
hashes.Add(hash);
return;
}
throw new ArgumentException("Cannot add duplicate item");
}
public void RemoveAt(int index)
{
var item = items[index];
hashes.Remove(item.GetHashCode());
items.RemoveAt(index);
}
还有剩菜:
public T this[int index]
{
get { return items[index]; }
set { Insert(index, value); }
}
public int Count => items.Count;
public bool Contains(T item) => hashes.Contains(item.GetHashCode());
public IEnumerator<T> GetEnumerator() => items.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => items.GetEnumerator();
就是这样。现在你有了列表实现,它只会添加一次(第一次)。例如
var list = new ListWithoutDuplicates<int> { 1, 2, 1, 3, 5, 2, 5, 3, 4 };
将创建包含项目 1、2、3、5、4 的列表。注意:如果内存消耗比性能更重要,则不要使用哈希,而是使用 O(n) 的 items.Contains 操作。
顺便说一句,我们刚刚做的实际上是一个 IList Decorator