您可以在插入时通过简单地不插入已经存在的水果来控制它
if (!myFruits.Any(f => f.Weight == newFruit.Weight))
myFruits.Add(newFruit);
如果您无法操作插入逻辑,则可以创建一个自定义列表,该列表包含一个普通的List<T>并更改Add上述示例中的行为:
public class FruitsWithDistinctWeightList : IEnumerable<Fruit>
{
private List<Fruit> internalList;
... // Constructor etc.
public void Add(Fruit fruit)
{
if (!internalList.Any(f => f.Weight == fruit.Weight))
internalList.Add(fruit);
}
... // Further impl of IEnumerable<Fruit> or IList<Fruit>
}
您还可以使用一些不允许重复项的现有集合。例如一些基于哈希的集合,例如HashSet<Fruit>:
var fruitsWithDistinctWeight = new HashSet<Fruit>(new FruitWeightComparer());
你会使用一个比较器说重量相等的水果是相等的:
public class FruitWeightComparer : IEqualityComparer<Fruit>
{
public bool Equals(Fruit one, Fruit two)
{
return one.Weight == two.Weight;
}
public int GetHashCode(Fruit item)
{
return one.Weight.GetHashCode();
}
}
请注意, aHashSet<T>不像列表那样排序。请注意,为简单起见,上面的所有代码都假设设置了 Weight 字段。如果您的班级有公共设置者(即不保证这一点),则必须进行适当的更改。