You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取LINQ查询中匹配列表项的索引?代码报错求解决

LINQ Join中获取匹配项索引的正确写法

你的代码报错是因为在select里错误地写了lambda表达式,这不仅拿不到索引,还会导致编译失败。要在Join结果里获取匹配元素的索引,得先给目标集合的元素带上索引信息,再执行Join操作。

修正后的代码

public class Test
{
    public int a;
    public string b;

    public Test(int x, string y) { a = x; b = y; }
}         

List<Test> a1= new List<Test>();  
List<Test> b1= new List<Test>();  

a1.Add(new Test(1, "test1-a"));
a1.Add(new Test(2, "test2-a"));
a1.Add(new Test(3, "test3-a"));
a1.Add(new Test(4, "test4-a"));

b1.Add(new Test(3, "test3-b"));
b1.Add(new Test(4, "test4-b"));
b1.Add(new Test(5, "test5-b"));
b1.Add(new Test(6, "test6-b"));

// 先给b1的每个元素绑定它在原列表中的索引
var bWithIndex = b1.Select((item, index) => new { Item = item, Index = index });

// 基于a字段做Join,同时获取匹配的索引
var result = from m in a1
             join n in bWithIndex 
             on m.a equals n.Item.a
             select new { MatchedAValue = m.a, BItemIndex = n.Index };

// 输出结果
foreach (var item in result)
{
    Console.WriteLine($"({item.MatchedAValue}, {item.BItemIndex})");
}

运行结果

(3, 0)
(4, 1)

这和你期望的结果(推测是笔误,原描述的(2,0)应为(3,0))一致。

关键说明

  • LINQ的Join本身不提供索引信息,必须通过Select((item, idx) => ...)方法为元素附加索引,这个重载会自动传入元素在序列中的位置。
  • 如果你需要获取a1中匹配元素的索引,只需要对a1做同样的索引绑定操作即可。
  • 你原代码里的select((index) => new { index, n.b })是错误的,这里的select是针对每个Join后的匹配项,不能直接写lambda来“获取”索引,而是要先提前准备好索引数据。

内容的提问来源于stack exchange,提问作者Nijaguna

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 23:32:45