Aranfea Aranfea - 18 days ago 4
C# Question

C# Comapre two list and return value and index

How can I compare two string lists and return this same value and index one of the list ?

Example:

a = List<string> {a,b,c};
b = List<string> {d,a,c};


I need return
c
and index
3
,
a
and index
1


I have only compare now :

var duplicateProduct = productIdList.Where(b => allProduct.Any(a => b.Contains(a)));


Thanks for help.

Answer
 List<string> listA = new List<string>() { "a", "b", "c" };
 List<string> listB = new List<string>() { "d", "a", "c" };

 var result = listA.Select((x, y) => new { element = x, index = y })
    .Where(z => listB.Contains(z.element));

EDIT: if you don't want a 0 based index, you can do this instead:

var result = listA.Select((x, y) => new { element = x, index = y += 1 })
   .Where(z => listB.Contains(z.element));

EDIT2: get duplicates from both lists

var list1_duplicates = listA.Select((x, y) => new { element = x, index = y })
           .Where(z => listB.Contains(z.element));

var list2_duplicates = listB.Select((x, y) => new { element = x, index = y })
           .Where(z => listA.Contains(z.element));

var all_duplicates = list1_duplicates.Concat(list2_duplicates);