使用Select和Indexer的Linq - c#

我有以下查询在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();

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

select new { ContainerID = container.ContainerID, TypeID = container.ContainerTypeID, ContainerIndex = index  };

我似乎无法正确理解的是选择使用选择索引器的正确语法。

谢谢你的帮助。

参考方案

您无法使用查询表达式格式获取索引,但是可以用点表示法使用overload for 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 });

Java中的OrderByDecending(LINQ)等效项 - java

嗨,我是一名使用Java的C#开发人员。问题很简单:我如何才能将下面的c#代码写入Java并仍能正常工作:myCoffeeList.OrderByDescending(x => x.Name?.ToLower()?.Trim() == sender.Text.ToLower()?.Trim())); 我的sender.Text基本上是一个文本框。文本的…

Linq-在嵌套集合中查找元素 - c#

我有一个通用列表-SupportedTypeGroups。每个SupportedTypeGroup都有SupportedTypes属性(SupportedType的通用列表)。如何构造Linq查询以使用所需名称查找SupportedType? 参考方案 var result = SupportedTypeGroups .SelectMany(g => …

Linq FirstOrDefault评估每次迭代的谓词吗? - c#

如果我有如下声明:var item = Core.Collections.Items.FirstOrDefault(itm => itm.UserID == bytereader.readInt()); 这段代码是在每次迭代时从我的流中读取一个整数,还是只读取一次该整数,将其存储,然后在整个查找过程中使用其值? 参考方案 考虑以下代码: static …

LINQ RemoveAll代替循环 - c#

我有两个for循环,用于从列表中删除项目。我正在为这些循环寻找等效的LINQ语句for (Int32 i = points.Count - 1; i >= 0; i--) { for (Int32 j = touchingRects.Count - 1; j >= 0; j--) { if (touchingRects[j].HitTest(po…

Linq Any()的哪种使用效率更高? - c#

我有一个Linq查询,如下所示:return this._alarmObjectAlarmViolationList .Where(row => row.ObjectId == subId) .Where(row => row.AlarmInternalId == "WECO #1 (StdDev > UCL)") .W…