[英]How to find a specific element in a List
I want to filter my List
and if an item
already exists , I don't want to add that item
to that List
.我想过滤我的
List
,如果一个item
已经存在,我不想将该item
添加到该List
。 That's why I try to filter by the item
property.这就是我尝试按
item
属性过滤的原因。
if(!(PolyLineList.Contains(PolyLineList.Find(x => x.item == item))))
{
cPolyline currentPolyLine = new cPolyline(pointlist,item);
PolyLineList.Add(currentPolyLine);
}
When an item
already exists in PolyLineList
, that is equal to item
, it should skip the if
-statement.当
PolyLineList
中已经存在item
item
,它应该跳过if
语句。
You may want to change List<T>
to HashSet<T>
and just Add
(providing that PolyLine
implements Equals
and GetHashCode
methods for PolyLine
instances to be compared):您可能希望将
List<T>
更改为HashSet<T>
并仅Add
(假设PolyLine
为要比较的PolyLine
实例实现Equals
和GetHashCode
方法):
//TODO: you, probably, want to rename PolyLineList into PolyLineSet or something
HashSet<cPolyline> PolyLineList = new HashSet<cPolyline>();
...
PolyLineList.Add(currentPolyLine);
Assuming the type of item
is ItemType
:假设
item
的类型是ItemType
:
var itemSet = new HashSet<ItemType>();
... ...
if (itemSet.Add(item))
{ // item is unique
PolyLineList.Add(new cPolyline(pointlist,item));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.