Get index of a List <> element based on C # using Linq

This is a fairly simple question, I have a list of objects that have an Identifier field identifier.

How can I get the index of an object in the list if I know the ID?

Example:

 CUSTOM_OBJECTS test = new CUSTOM_OBJECTS{ID=50}; List<CUSTOM_OBJECTS> List = new List<CUSTOM_OBJECTS>(); List.Add(test); 

I would like to get the index of the object with ID = 50 in the list, which will be 0 in this example.

+4
source share
2 answers
 var index = List.FindIndex(x=>x.ID==50); 
+15
source
 CUSTOM_OBJECT singleObject = list.Single(co => co.ID == 50) 

You can also use the SingleOrDefault, First, or FirstOrDefault methods.

-3
source

Source: https://habr.com/ru/post/1347677/


All Articles