A Utility function with parameter as index of list<> RRS feed

  • Question

  • User1052662409 posted

    Hi All,

    I need to add a function to my Utility class which will take a integer as a parameter and return the index of a list<> according to the given parameter.

    Suppose I give 4 in parameter it will return the 4th index of a list<>

    Any reference, any source?

    here I have created one

    public static int Get_Index(int i)
            List<int> MyList = new List<int>();
            int index = MyList.IndexOf(i);
            return index;


    Wednesday, March 14, 2018 7:03 AM


All replies

  • User475983607 posted

    It seems that you are confusing index with a list item.

    To get the 4th index of a List<T>.  subtract one because the index starts at 0; ie 0,1,2,3

    int i = 4;
    var result = MyList[i-1];

    See the C# Generics programming guide


    Also see Arrays


    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, March 14, 2018 2:48 PM
  • User303363814 posted

    Do you mean "return the 4th index of a list<>"?  Because the 4th index is 4 (or 3 if you count from 0).

    Do you actually want to know the index of the first entry in the List which has a value of 4.  That is, if the LIst is (10, 9, 8 , 7 , 6, 5, 4, 3, 4, 5) do you want the answer of 6?

    var indexOfFirstN = myList.FindIndex(i => i==N);

    Wednesday, March 14, 2018 11:26 PM
  • User-1838255255 posted

    Hi demoninside9,

    According to your needs, as far as i know, you don't want get the the index of the item in list, i make a sample, please check: 

    protected void Page_Load(object sender, EventArgs e)
                int index = Get_Index(3);
    public static int Get_Index(int i)
                List<int> list = new List<int>(new int[] { 1, 2, 3, 10, 7 });
                int index = list.FindIndex(a => a == i);
                return index;

    Best Regards,

    Eric Du 

    Thursday, March 15, 2018 10:33 AM