1

I want to filter my List and if an item already exists, I don't want to add that item to that List. That's why I try to filter by the item property.

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.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Lion Hunter
  • 89
  • 1
  • 8

3 Answers3

1

Use Linq's Any method:

if (!PolyLineList.Any(x => x.item == item))
{
    ...
}
canton7
  • 37,633
  • 3
  • 64
  • 77
  • This will slow down greatly as the list grows. https://stackoverflow.com/a/10762995/9945524 – Mark Cilia Vincenti Oct 30 '19 at 13:12
  • @MarkCiliaVincenti Of course it will, that goes without saying. I did have an edit which suggested keeping a separate HashSet of the `item` property, but it was hard to articulate clearly without knowing much of the context (such as the type of the `item` property), given that the OP is obviously fairly inexperienced. – canton7 Oct 30 '19 at 13:14
  • that's just what my answer is doing, unless I misunderstood you. – Mark Cilia Vincenti Oct 30 '19 at 13:15
  • 1
    @MarkCiliaVincenti It is, yes. Although I think that could be unclear to the OP - you need to make it clear that items are removed from `itemSet` when they're removed from `PolyLineList`, and that `itemSet` and `PolyLineList` need to have the same storage duration, for instance. – canton7 Oct 30 '19 at 13:15
1

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):

 //TODO: you, probably, want to rename PolyLineList into PolyLineSet or something 
 HashSet<cPolyline> PolyLineList = new HashSet<cPolyline>();

 ...

 PolyLineList.Add(currentPolyLine);
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
  • 1
    Note that 1) this relies on the OP overriding `Equals` and `GetHashCode` in `cPolyline` to do equality based only on the `name` member, and 2) assumes that order in `PolyLineList` is not relevant. – canton7 Oct 30 '19 at 10:04
1

Assuming the type of item is ItemType:

var itemSet = new HashSet<ItemType>();

...

if (itemSet.Add(item))
{ // item is unique
    PolyLineList.Add(new cPolyline(pointlist,item));
}
Mark Cilia Vincenti
  • 1,410
  • 8
  • 25