Home > OS >  I want to show a list item's index in a loop
I want to show a list item's index in a loop

Time:11-05

        List<string> lst = new List<string>() { "mahdi","arshia","amir"};

        int a = 0;
        var list_mian = lst[a];

        for (int i = a; i <Convert.ToInt16(list_mian); i  ) //Additional information: Input string was not in a correct format.
        {
            MessageBox.Show(lst.IndexOf(lst[0]).ToString());
        }

I want to show a list item's index in a loop, for example of mahdi's index is 0 and amir's index is 2 i wanna show their index respectively in a "for" loop and i give an error that i show that in the code part

CodePudding user response:

Your trying to convert an integer to a string and then use that as a range on the for loop just use .count and compare it to the name attached to that index of the list. Hope you find this useful.

    public static int? findPerson(string name)
    {
        List<string> lst = new List<string>() { "mahdi", "arshia", "amir" };
        int? result = null;
        for (int i = 0; i < lst.Count; i  ) //Additional information: Input string was not in a correct format.
        {
            if (lst[i] == name)
            {
                result = i;
            }
        }
        return result;
    }
    static void Main(string[] args)
    {
        var index = findPerson("arshia");
        if (index == null)
        {
            Console.WriteLine("PersonNotFound");
        }
        else {
            Console.WriteLine("Index of "   index.ToString());
        
        }
    }

CodePudding user response:

You can do it with IndexOf it returns the index or -1 when there is no item.

List<string> list = new List<string>() { "mahdi", "arshia", "amir" };
var indexOfAmir = list.IndexOf("amir"); // 2
var indexOfMax = list.IndexOf("max"); // -1
  • Related