how to check if object already exists in a list

前端 未结 9 1727
梦谈多话
梦谈多话 2020-11-28 05:41

I have a list

  List myList

and I am adding items to a list and I want to check if that object is already in the list.

相关标签:
9条回答
  • 2020-11-28 06:06

    It depends on the needs of the specific situation. For example, the dictionary approach would be quite good assuming:

    1. The list is relatively stable (not a lot of inserts/deletions, which dictionaries are not optimized for)
    2. The list is quite large (otherwise the overhead of the dictionary is pointless).

    If the above are not true for your situation, just use the method Any():

    Item wonderIfItsPresent = ...
    bool containsItem = myList.Any(item => item.UniqueProperty == wonderIfItsPresent.UniqueProperty);
    

    This will enumerate through the list until it finds a match, or until it reaches the end.

    0 讨论(0)
  • 2020-11-28 06:11

    Simple but it works

    MyList.Remove(nextObject)
    MyList.Add(nextObject)
    

    or

     if (!MyList.Contains(nextObject))
        MyList.Add(nextObject);
    
    0 讨论(0)
  • 2020-11-28 06:12

    Simply use Contains method. Note that it works based on the equality function Equals

    bool alreadyExist = list.Contains(item);
    
    0 讨论(0)
提交回复
热议问题