【问题标题】:Returning Index in Enumerable Select可枚举选择中的返回索引
【发布时间】:2010-03-29 16:15:55
【问题描述】:

我有一个List<MyClass>,其中包含 2 个具有 SequenceNumber 属性的项目。

如果我在下面使用此代码,则返回的索引是 0 而不是 1:

var test = TrackingCollection
                .Where(x =>  x.SequenceNumber == 2)
                .Select((item, index) =>
                                    new
                                    {
                                         index, item.SequenceNumber
                                    });

这是因为它在我的新匿名类型中将 0 称为索引,还是因为我只需要增加一些基于零索引的怪异。

我所追求的是返回 TrackingCollection 中序列号为 2 或 887 的索引或原始集合中的任何其他正确索引...

【问题讨论】:

    标签: c# linq .net-3.5 c#-3.0 ienumerable


    【解决方案1】:

    听起来您的问题是在索引列表之前对其进行过滤。生成索引后需要过滤。简单的把 Where 子句放在后面:

    var test = TrackingCollection 
                .Select((item, index) => 
                                    new 
                                    { 
                                         index, item.SequenceNumber 
                                    })
                .Where(x =>  x.SequenceNumber == 2);
    

    【讨论】:

      【解决方案2】:

      为什么不应该是零? C# 的集合索引默认从零开始。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-12-23
        • 2011-12-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-10-17
        相关资源
        最近更新 更多