Reputation: 19544
I know I could very easily accomplish this using loops, but I'm looking for the most efficient solution for my question.
Suppose I have 2 lists(of string):
Dim lst1 as new list(of string)
Dim lst2 as new list(of string)
And both have the same number of elements, for example:
Lst1: Lst2:
a abc1
a abc2
b abc3
a abc4
b abc5
c abc6
a abc7
c abc8
Now, I'm looking to get, for example, all the elements from lst2 for which the corresponding elements in Lst1 = "a"
So my final result will be:
Lst3 = Items from Lst2 where corresponding Items in Lst1 = "a"
Lst3 = {abc1, abc2, abc4, abc7}
Again, I know this would be SUPER easy to do with loops, but I'm wondering how to do this via Linq.
Thanks!!!
Upvotes: 0
Views: 1197
Reputation: 14282
In a more generic way you could try some thing like this :
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()
Hope this will help !!
Upvotes: 0
Reputation: 116098
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();
Upvotes: 2
Reputation: 81233
Try this -
List<String> Lst3 = Lst2.Where((item, index) =>
Lst1[index].Equals("a")).ToList();
Upvotes: 1