Provided both lists have the same length, you could use Zip
to pair up the corresponding items from both sequences:
var target = "B";
var result = list1.Zip(list2, (x,y) => Tuple.Create(x,y))
.Where(o => o.Item1 == target);
foreach(var item in result)
{
Console.WriteLine(item.Item2);
}
I used a Tuple
, so Item1
is the letter from list1
and Item2
is the corresponding item in list2
. Of course you could've used an anonymous type and given it a more meaningful name instead.
UPDATE: I just noticed that you tagged the question with C#-3.0. In that case, use the solution below. Zip
and Tuple
were introduced in .NET 4.0. The solution below uses the Select
method, which was available in .NET 3.5. Both solutions use LINQ, so you need to add the namespace: using System.Linq;
Another solution is to use the overloaded Select
method to get the indices of the target letter, then grabbing the items from the second list based on those indices.
var target = "B";
var targetIndices = list1.Select((o, i) => new { Value = o, Index = i })
.Where(o => o.Value == target);
var query = targetIndices.Select(o => list2[o.Index]);
foreach(var item in query)
{
Console.WriteLine(item);
}