How can I delete a list item, knowing only its value. For example,

List <string> names = new List<string>(); names[0]="Ivan"; names[1]="Dima"; 

From this list, you need to delete an element with the name Dima, without referring to the number in this list, knowing only its name.

  • 3
    Specify - if there are several elements in the list with the name "Dima" - do you need to delete everything? - Zufir
  • @Zufir will not have similar elements - ZOOM SMASH
  • If there are no similar elements, I recommend using HashSet <string> . Will work faster. - RusArt

4 answers 4

If we are talking about strings or value types, then the Remove method is appropriate.

 List<string> names = new List<string>(2); names.Add("Ivan"); names.Add("Dima"); names.Remove("Dima"); 

To use it with classes, the class must implement IEquatable<T> , for comparison. Otherwise, the comparison will occur using Object.Equals , which for reference types is equivalent to comparing references.

    You can get a new list in which there are no elements with the value "Dima":

     names=names.Where(x=>x!="Dima").ToList() 

      You can use the Remove method

       names.Remove("Дима") 
      • Only RemoveAll - Dmitriev may be several;) - Zufir
      • @Zufir, or you need to remove only one and then RemoveAll obviously does not fit - Grundy
      • Yes, you need to clarify. - Zufir
       var obj = (names.FirstOrDefault(o => o == "name")); if (obj != null) { int index = names.IndexOf(obj); names.RemoveAt(index); }