vb.net 使用 LINQ 获取列表中匹配值的索引
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18468536/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get index of matching value in List using LINQ
提问by Toby
I would like to be able to run a LINQ query on a BindingList(Of T) that returns the indexeswhere a list object member is equal to a particular value.
我希望能够在 BindingList(Of T) 上运行 LINQ 查询,该查询返回列表对象成员等于特定值的索引。
say I have a list of simple objects of class widget:
说我有一个类小部件的简单对象列表:
Public Class widget
Public Property foo As Integer
Public Property bar As String
End Class
Dim widgetList As BindingList(Of widget)
I'd like to be able to query the list some thing like the below:
我希望能够查询列表,如下所示:
Dim test As Integer = 5
Dim index = (From i In widgetList
Where i.foo = test
Select i.index).First
Such that 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 even be using LINQ)
这样的索引包含第一个 listItem 的索引,其中 widgetList.Item(index).foo = 5。这样做的最佳方法是什么?(或者我什至应该使用 LINQ)
I have seen several C# methods to do this but Im not sufficiently au fait with C# to understand how to use them in VB
我已经看到了几种 C# 方法来做到这一点,但我对 C# 的了解不够充分,无法理解如何在 VB 中使用它们
回答by Ahmad Mageed
It's possible to achieve with LINQ by using the fluent syntax since there's an overloaded version of the Selectextension method that lets you get the index of the items.
可以通过使用 fluent 语法使用 LINQ 实现,因为有一个Select扩展方法的重载版本,可让您获取项目的索引。
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 the SelectI'm projecting the Widget as is, using o, and the iparameter represents the index. Next I use FirstOrDefaultwith a predicate to evaluate Foo(you could've used Wherefollowed by FirstOrDefault, but this is shorter). You should use FirstOrDefaultinstead of just Firstin case none of the items are found; FirstOrDefaultwill return null if nothing is found, whereas Firstwould throw an exception. That's why the next step is to check the result and make sure it isn't null.
在Select我按原样投影 Widget 时,使用o,i参数表示索引。接下来我使用FirstOrDefault一个谓词来评估Foo(你可以使用Where后跟FirstOrDefault,但这个更短)。您应该使用FirstOrDefault而不是First在没有找到任何项目的情况下使用;FirstOrDefault如果未找到任何内容,将返回 null,而First将引发异常。这就是为什么下一步是检查结果并确保它不为空的原因。
回答by Toby
I have also found a working solution as below, though I am not sure if this is any better or worse than the other answers.
我还找到了如下可行的解决方案,但我不确定这是否比其他答案更好或更差。
Dim index = Enumerable.Range(0, widgetList.Count) _
.Where(Function(i) widgetList.Item(i).foo = test) _
.First

