使用LINQ查找另一个数组中元素的索引 [英] Finding the indices of the elements of one array in another using LINQ
问题描述
给定两个数组A和B,从B元素的A中找到索引
Dim A As String()= { a,b,c,d,e,f,g,h,i}
Dim B As String()= {b ,d,e}
For Each item As String In B
Dim index1 As Integer = Array.IndexOf(A,item)
Console.WriteLine( {0} {1},index1,item)
下一个
1 b
3 d
4 e
我的尝试:
我在'传统'VB.NET中的代码有效,但我想用LINQ转换它。
先谢谢。
ATeDe
这是一种方式...
Dim A As String ()= { a, b, c, d, e, f, g, h, i}
Dim B As 字符串()= { b, d, e}
Dim c = A. 选择(功能(x,i)新 KeyValuePair( Of 字符串,整数)(x,i))_
。 Where( Function (x)B.Contains(x.Key))
For 每个项在 c
Console.WriteLine( {0} - {1},item.Key,item.Value)
下一步跨度>
作为 Graeme_Grant 的解决方案#1的替代方案[ ^ ],一个翻译过的(到Linq查询)版本的你的解决方案是:
Dim A As String ()= { a, b, c, d, e, f, g, h, i}
Dim B 作为 String ()= { b, d, e}
Dim result = A.Where( Function (q) B.Any( Function (w)q = w))。 _
选择(功能(x)新增功能 使用 _
{_
.Index = Array.IndexOf(A,x),_
.Value = x _
})
我建议查看以下MSDN文档以获取更多详细信息:
Enumerable.Intersect(TSource)方法(IEnumerable(TSource),IEnumerable (TSource))(System.Linq) [ ^ ]
Enumerable.Except(TSource)方法(IEnumerable(TSource),IEnumerable(TSource))(System.Linq) [ ^ ]
Enumerable.ElementAt(TSource)方法(IEnumerable(TSource),Int32)(System.Linq) [ ^ ]
Given two arrays A and B, find the index from A of the element of B
Dim A As String() = {"a", "b", "c", "d", "e", "f", "g", "h", "i"} Dim B As String() = {"b", "d", "e"} For Each item As String In B Dim index1 As Integer = Array.IndexOf(A, item) Console.WriteLine("{0} {1}", index1, item) Next
1 b
3 d
4 e
What I have tried:
My code in 'traditional' VB.NET works, but I want to convert it using LINQ.
Thanks in advance.
ATeDe
Here is one way...
Dim A As String() = {"a", "b", "c", "d", "e", "f", "g", "h", "i"} Dim B As String() = {"b", "d", "e"} Dim c = A.Select(Function(x, i) New KeyValuePair(Of String, Integer)(x, i)) _ .Where(Function(x) B.Contains(x.Key)) For Each item In c Console.WriteLine("{0} - {1}", item.Key, item.Value) Next
As an alternative to solution#1 of Graeme_Grant[^], a "translated" (to Linq query) version of your solution is:
Dim A As String() = {"a", "b", "c", "d", "e", "f", "g", "h", "i"} Dim B As String() = {"b", "d", "e"} Dim result = A.Where(Function(q) B.Any(Function(w) q=w)). _ Select(Function(x) New With _ { _ .Index = Array.IndexOf(A, x), _ .Value = x _ })
I'd suggest to check the following MSDN documentation for more details:
Enumerable.Intersect(TSource) Method (IEnumerable(TSource), IEnumerable(TSource)) (System.Linq)[^]
Enumerable.Except(TSource) Method (IEnumerable(TSource), IEnumerable(TSource)) (System.Linq)[^]
Enumerable.ElementAt(TSource) Method (IEnumerable(TSource), Int32) (System.Linq)[^]
这篇关于使用LINQ查找另一个数组中元素的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!