Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the index of next matching element in list using LINQ

Tags:

c#

linq

i have a list say :

List<string> list = new List<string>(){"Oracle","SQL Server","Java","Oracle","Python"};

Now i'm trying to get index of the second "Oracle" from the list using LINQ:

var indexFirefox = list.FindIndex(a => a.Text == "Oracle");

But this will give you only the first instance that is index 0. I want index as 4 in my result. Will using Skip help or there is a more simplistic way of getting the index. The example above is just a demo, i have a list with over 300 values.

like image 681
vivek singh Avatar asked Aug 07 '16 21:08

vivek singh


People also ask

How do you find the index of an element in Linq?

LINQ does not have an IndexOf method. So to find out index of a specific item we need to use FindIndex as int index = List. FindIndex(your condition); 0.

How do I find the next record in Linq?

First(); var next = items . OrderBy(item => item.Id) . First(item => item.Id > currentId); var next = items .

How to check if an item already exists in a List in C#?

public bool Contains (T item); Here, item is the object which is to be locate in the List<T>. The value can be null for reference types. Return Value: This method returns True if the item is found in the List<T> otherwise returns False.

Can we use Linq on list in C#?

Using LINQLINQ features can be used in a C# program by importing the System.


1 Answers

So many Linq answer when there already exists one method doing the job (given in the first comment)

List<T>.FindIndex has an overload which takes an additional index parameter to search only from that index.

So to get the second occurrence of an item you just have to use that overload with the result of a "regular" FindIndex.
(Note: in your question's sample you used a.Text but items are string so there is no Text property)

var firstIndex = list.FindIndex (item => item == "Oracle");
if (firstIndex != -1)
{
    var secondIndex = list.FindIndex (firstIndex, item => item == "Oracle");
    // use secondIndex (can be -1 if there is no second occurrence)
}

And with your sample example secondIndex will be 3 (and not 4 as stated in your question, indexes are zero-based)

Alternatively if you want to get occurrence indexes in turn you can loop using that same method.

// defined here to not have to repeat it 
Predicate<string> match = item => item == "Oracle";

for (var index = list.FindIndex (match); index > -1; index = list.FindIndex (index + 1, match))
{
    // use index here
}

Or if you prefer a while loop

var index = list.FindIndex (match);

while (index > -1)
{
    // use index here

    index = list.FindeIndex (index + 1, match);
}
like image 116
Sehnsucht Avatar answered Sep 22 '22 04:09

Sehnsucht