HajdaCZ
HajdaCZ

Reputation: 83

List search by index?

I'm trying to search for the index of the first list item, which has the value "hello" and it's index is higher than 15. This is apparently not the way, because when I refer to p, I refer to the value, not the string itself (IndexOf looks up the index of the first occurence of "hello" in the list, because p == string)

int soucasny = list1.FindIndex(p => p == "hello" || list1.IndexOf(p) > 15);

Is there a way to achieve the desired result? Select probably?

Upvotes: 2

Views: 207

Answers (3)

Habib
Habib

Reputation: 223412

Use List<T>.FindIndex Method (Int32, Predicate<T>) which takes a predicate and specifies the index to start search like:

int soucasny = list1.FindIndex(15, p => p == "hello");

If you have List<string> then using List<T>.IndexOf would give you the result, but if you have a list of custom objects then you may need predicate. Like:

List<Student> studentList = new List<Student>();
int index = studentList.FindIndex(15, p=> p.StudentName == "Some Name");

Upvotes: 2

Mike Strobel
Mike Strobel

Reputation: 25623

@Selman22 provides the most correct and efficient answer for your exact question. I offer the following merely as an addendum, for cases where you may have a non-List sequence or need access to an element's index from within your filter expression:

public static int FirstIndexWhere<T>(
    this IEnumerable<T> sequence,
    Func<T, int, bool> predicate)
{
    if (sequence == null)
        throw new ArgumentNullException("sequence");
    if (predicate == null)
        throw new ArgumentNullException("predicate");

    var index = 0;

    for (var enumerator = sequence.GetEnumerator(); enumerator.MoveNext(); ++index)
    {
        if (predicate(enumerator.Current, index))
            return index;
    }

    return -1;
}

Example usage:

int soucasny = list1.FirstIndexWhere((p, i) => p == "hello" && i > 15);

Upvotes: 1

Selman Gen&#231;
Selman Gen&#231;

Reputation: 101732

You can specify a start index for IndexOf

int soucasny = list1.IndexOf("hello", 15);

Upvotes: 9

Related Questions