How to get the index of an item in a list in a single step?

后端 未结 8 1053
旧巷少年郎
旧巷少年郎 2020-11-27 11:16

How can I find the index of an item in a list without looping through it?

Currently this doesn\'t look very nice - searching through the list for the same item twice

8条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-27 12:02

    If you don't want to use LINQ, then:

    int index;
    for (int i = 0; i < myList.Count; i++)
    {
        if (myList[i].Prop == oProp)
        {
           index = i;
           break;
        }
    }
    

    this way you are iterating list only once.

提交回复
热议问题