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

后端 未结 8 1023
旧巷少年郎
旧巷少年郎 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 11:38

    EDIT: If you're only using a List<> and you only need the index, then List.FindIndex is indeed the best approach. I'll leave this answer here for those who need anything different (e.g. on top of any IEnumerable<>).

    Use the overload of Select which takes an index in the predicate, so you transform your list into an (index, value) pair:

    var pair = myList.Select((Value, Index) => new { Value, Index })
                     .Single(p => p.Value.Prop == oProp);
    

    Then:

    Console.WriteLine("Index:{0}; Value: {1}", pair.Index, pair.Value);
    

    Or if you only want the index and you're using this in multiple places, you could easily write your own extension method which was like Where, but instead of returning the original items, it returned the indexes of those items which matched the predicate.

    0 讨论(0)
  • 2020-11-27 11:38

    If anyone wonders for the Array version, it goes like this:

    int i = Array.FindIndex(yourArray, x => x == itemYouWant);
    
    0 讨论(0)
  • 2020-11-27 11:46
    1. Simple solution to find index for any string value in the List.

    Here is code for List Of String:

    int indexOfValue = myList.FindIndex(a => a.Contains("insert value from list"));
    
    1. Simple solution to find index for any Integer value in the List.

    Here is Code for List Of Integer:

        int indexOfNumber = myList.IndexOf(/*insert number from list*/);
    
    0 讨论(0)
  • 2020-11-27 11:58

    For simple types you can use "IndexOf" :

    List<string> arr = new List<string>();
    arr.Add("aaa");
    arr.Add("bbb");
    arr.Add("ccc");
    int i = arr.IndexOf("bbb"); // RETURNS 1.
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-27 12:04

    How about the List.FindIndex Method:

    int index = myList.FindIndex(a => a.Prop == oProp);
    

    This method performs a linear search; therefore, this method is an O(n) operation, where n is Count.

    If the item is not found, it will return -1

    0 讨论(0)
提交回复
热议问题