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.
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.
First(); var next = items . OrderBy(item => item.Id) . First(item => item.Id > currentId); var next = items .
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.
Using LINQLINQ features can be used in a C# program by importing the System.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With