简体   繁体   English

如何在列表中查找特定元素

[英]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语句。

Use Linq's Any method:使用 Linq 的Any方法:

if (!PolyLineList.Any(x => x.item == item))
{
    ...
}

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实例实现EqualsGetHashCode方法):

 //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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM