Get the match index of a value in a list using LINQ

I would like to be able to run a LINQ query on a BindingList (Of T) that returns indexes where the list item is equal to a specific value.

Let's say I have a list of simple widget objects of a class:

Public Class widget Public Property foo As Integer Public Property bar As String End Class Dim widgetList As BindingList(Of widget) 

I would like to be able to request something like below from the list:

 Dim test As Integer = 5 Dim index = (From i In widgetList Where i.foo = test Select i.index).First 

So the index contains the index of the first listItem, where widgetList.Item (index) .foo = 5. What is the best way to do this? (Or should I use LINQ)

I have seen several C # methods for this, but Im not sure enough about C # to figure out how to use them in VB

+6
source share
2 answers

This can be achieved using LINQ, using the free syntax, since there is an overloaded version of the Select extension method that allows you to get the index of elements.

Try this approach:

 Dim test As Integer = 5 Dim query = widgetList.Select(Function(o,i) New With { .Widget = o, .Index = i}) _ .FirstOrDefault(Function(item) item.Widget.Foo = test) If query Is Nothing Console.WriteLine("Item not found") Else Console.WriteLine("Item found at index {0}", query.Index) End If 

In Select I design the widget as is using o , and the parameter i represents the index. Then I use FirstOrDefault with a predicate to evaluate Foo (you could use Where and then FirstOrDefault , but this is shorter). You should use FirstOrDefault instead of First if none of the elements are found; FirstOrDefault returns null if nothing is found, while First throws an exception. That is why the next step is to check the result and make sure that it is not null.

+6
source

I also found a working solution as shown below, although I'm not sure if this is better or worse than the other answers.

 Dim index = Enumerable.Range(0, widgetList.Count) _ .Where(Function(i) widgetList.Item(i).foo = test) _ .First 
+1
source

Source: https://habr.com/ru/post/952596/


All Articles