0

我知道我可以很容易地使用循环来完成这个,但我正在为我的问题寻找最有效的解决方案。

假设我有 2 个列表(字符串):

Dim lst1 as new list(of string)
Dim lst2 as new list(of string)

并且两者都具有相同数量的元素,例如:

Lst1:    Lst2:
a        abc1
a        abc2
b        abc3
a        abc4
b        abc5
c        abc6
a        abc7
c        abc8

现在,例如,我正在寻找来自 lst2 的所有元素,其中 Lst1 = "a" 中的相应元素

所以我的最终结果将是:

Lst3 = Items from Lst2 where corresponding Items in Lst1 = "a"
Lst3 = {abc1, abc2, abc4, abc7}

再一次,我知道这对循环来说非常容易,但我想知道如何通过 Linq 做到这一点。

谢谢!!!

4

3 回答 3

2
List<string> Lst1 = new List<string> { "a", "a", "b", "a", "b", "c", "a", "c"};
List<string> Lst2 = new List<string> { "abc1", "abc2", "abc3", "abc4", "abc5", "abc6", "abc7", "abc8" };

var Lst3 = Lst2.Where((s, i) => Lst1[i] == "a").ToList();
于 2012-10-24T16:50:06.847 回答
1

尝试这个 -

List<String> Lst3 = Lst2.Where((item, index) =>
                              Lst1[index].Equals("a")).ToList();
于 2012-10-24T16:49:25.007 回答
0

以更通用的方式,您可以尝试这样的事情:

C#

List<String> lst3 = lst2.Where((item, index) => 
                               item.StartsWith(lst1.Distinct()[index])).ToList();

VB

Dim lst3 As List(Of [String]) = lst2.Where(Function(item, index)
                                item.StartsWith(lst1.Distinct()(index))).ToList()

希望这会有所帮助!

于 2012-10-24T16:55:09.920 回答