In C#, Is It Possible To Obtain The Index Of An Item In A List In Just One Step?

To get the index of an item in a list in a single step in C#, you can use the FindIndex method available in the System.Collections.Generic.List class.

Here’s an example:

List<int> numbers = new List<int> { 10, 20, 30, 40, 50 };

int index = numbers.FindIndex(x => x == 30);
Console.WriteLine(index); // Output: 2

int index2 = numbers.FindIndex(x => x == 55);
Console.WriteLine(index2); // Output: -1 (item not found)

In the above example, we have a list of integers called numbers. We use the FindIndex method and pass a lambda expression as an argument that specifies the condition for finding the desired item. The FindIndex method returns the index of the first occurrence of an item that matches the given condition. If no item is found, it returns -1.

Note that the FindIndex method throws an exception if the list is null, so make sure to check for null before using this method.

About the Author Rex

I'm a passionate tech blogger with an insatiable love for programming! From my early days tinkering with code, I've delved into web dev, mobile apps, and AI. Sharing insights and tutorials with the world is my joy, connecting me to a global community of like-minded tech enthusiasts. Python holds a special place in my heart, but I embrace all challenges. Constantly learning, I attend tech conferences, contribute to open-source projects, and engage in code review sessions. My ultimate goal is to inspire the next generation of developers and contribute positively to the ever-evolving tech landscape. Let's code together!