Linq使用Select和Indexer

Ran*_*der 2 c# linq

我有以下查询在LinqPad中成功运行:

    var results = 
    from container in Container
    join containerType in ContainerType on container.ContainerType equals containerType
    where containerType.ContainerTypeID == 2
    select new { ContainerID = container.ContainerID, TypeID = container.ContainerTypeID};

results.Dump();
Run Code Online (Sandbox Code Playgroud)

我想更改选择以使用索引器,以便选择看起来像这样:

select new { ContainerID = container.ContainerID, TypeID = container.ContainerTypeID, ContainerIndex = index  };
Run Code Online (Sandbox Code Playgroud)

我似乎无法做到的是选择使用select索引器的正确语法.

谢谢你的帮助.

Jon*_*eet 5

您无法使用查询表达式格式获取索引,但是您可以使用点符号来执行此操作的重载Select.您可以坚持使用大部分查询表达式格式,然后在额外的选择投影中添加索引:

var tmp = 
    from container in Container
    join containerType in ContainerType
      on container.ContainerType equals containerType
    where containerType.ContainerTypeID == 2
    select new { ContainerID = container.ContainerID,
                 TypeID = container.ContainerTypeID};

var results = tmp.Select((x, index) => new { x.ContainerID, x.TypeID, 
                                             ContainerIndex = index });
Run Code Online (Sandbox Code Playgroud)