如何比较两个字符串列表并返回第一个列表的相同值和索引?
示例:
a = List<string> {a,b,c};
b = List<string> {d,a,c};
我需要返回c
和索引3
,a
和索引1
我现在只是在比较:
var duplicateProduct = productIdList.Where(b => allProduct.Any(a => b.Contains(a)));
感谢您的帮助。
答案 0 :(得分:1)
var duplicateProduct = productIdList.Where(b => allProduct.Any(a => b.Contains(a)))
.Select(x => new { x, index = productIdList.IndexOf(x)});
这将在productIdList
列表中创建一个IEnumerable的匿名类型的项目和该项目的索引。
答案 1 :(得分:0)
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));
编辑:如果你不想要一个基于0的索引,你可以这样做:
var result = listA.Select((x, y) => new { element = x, index = y += 1 })
.Where(z => listB.Contains(z.element));
EDIT2:从两个列表中获取重复项
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);
EDIT3:代码的另一个更新,我们在每个元素的两个列表上检索索引,同时管理同一列表中的重复项
List<string> listA = new List<string>() { "a", "b", "c" };
List<string> listB = new List<string>() { "d", "a", "c", "a" };
var result = listA.Select((a) => new
{
element = a,
indexA = listA.IndexOf(a),
indexB = Enumerable.Range(0, listB.Count).Where(b => listB[b].Equals(a)).ToArray()
});
(可选)添加
.Where(a => listB.Contains(a.element));
之前的&#34;;&#34;仅检索第二个列表中的元素
答案 2 :(得分:0)
试试这个,它可能对你有帮助。
var al =new List<string> { "a","b","c"};
var bl = new List<string> { "d","a","c"};
var res = (from a in al
join b in bl
on a equals b
select new
{
Matched = a,
Index = al.IndexOf(a)
}).ToList();