Вопрос

I have two lists:

List1 has values like: "A, A, A, A, B, B, B, B, C, C, C, C, C... so on
List2 has values like: "0, 1, 2, 2, 1.1, 1.2, 1.3, 4, 4, 4, 4.... so on

I want to get index of List1 with values of lets say B and find corrosponding values in List2. What i am doing is getting start and end index of List1 where value is B. Than looping through list2 for those indexes and getting values. This seems like too much work and lot of overhead. Is there a better way of doing this using linq?

I used this: var list1Values = list1.FindAll(x => x.Contains("B")); This gives me values from B i am stuck after this like how can i get corresponding values from list2 after this? As findAll dont even give index. One thought is to loop through index of list1Values and get list2 values but dont think that is right way to do it.

Это было полезно?

Решение

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);
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top