- Home /
C# find specific piece of data and where it is in list
If I have 10 items in a list & a few get removed, I'm trying to figure out how to be able to not only check to see if a value still exists in a list, but if it does to also find where it is in the list's order.
static public List<float> myList = new List<float>();
myList.Add(1);
myListAdd(2);
myListAdd(3);
Debug.Log("I am at " + // where 3 is in order of the list, which would be [2] //);
myList.RemoveAt(1);
if ( // the number 3 exists in list // )
Debug.Log("Now I'm at " + // where 3 is in the list, which is now [1] //);
}
I've looked around, found pages that say things like List(T).Exists but couldn't figure out how to work it into code. Any help is much appreciated ^-^
Answer by BastianUrbach · Feb 23, 2018 at 06:20 AM
List.Exists expects a predicate, which is basically a condition that has to be true for an element to be considered of interest for the search. In your case, the simpler method List.Contains should be sufficient. It takes a list element and returns true if the list contains that element.
To find the position of an element, there are again two methods, one with predicate (List.FindIndex) and one that simply takes an element and returns its index (List.IndexOf).
Note that IndexOf does not cause an error if the element is not contained in the list but simply returns -1. This allows using just a single call to IndexOf instead of using Contains first.