There is a structure and a list of its objects. How to check the existence of an element with a specific index?

public static struct Coord { int id; int x; int y; public Coord(int _id, int _x, int _y) :this() { x = _x; y = _y; } } static List<Coord> house=new List<Coord>(); 

So nizyayaya!

 if (house.Count>1 && house[id]!=null) { } 

How can you?

  • four
    And so: if(id>=0 && id<house.Count){ } - qzavyer
  • one
    house [id]! = null - what is id ? Number sequence number of the record or id from the structure? - Zufir
  • record number, index of the item to be searched - Димка
  • so the structure cannot be null - Grundy

1 answer 1

You understand that id is generally not equal to the element index?

If you need to check that there is an element with a specific id in the list, you can use the Any extension method and make the structure fields public:

 public static struct Coord { public int id; ... } if (house.Any(_ => _.id == id)) { } 

If you need to find out if there is an element with a specific index, you can check that the index is in the range from 0 to the number of elements in the list (as @qzavyer noted in his comment):

 if (id >= 0 && id < house.Count) { }