简体   繁体   English

分组时如何在LINQ查询中添加索引?

[英]How can I add an index to a LINQ query when there is a grouping?

I have the following LINQ statement that works 我有下面的LINQ语句有效

     var separator = new[] { " ||| " };
        var objectives = data.Select(s => s.Split(separator, StringSplitOptions.RemoveEmptyEntries))
            .GroupBy(strings => strings[0])
            .Select(grouping => new Objective
            {
                Text = grouping.Key,
                ObjectiveDetails = grouping.Select(s => new ObjectiveDetail { 
                    Text = s[1]
                }).ToList()
            })
            .ToArray();
        return objectives;
    }

What I would like to do is to populate a field called Number inside the Objective object and a field called Number inside the ObjectiveDetail object. 我想做的是在Objective对象内填充一个名为Number的字段,在ObjectiveDetail对象内填充一个名为Number的字段。 I want the number to start at one and be incremented so each new Objective and ObjectiveDetail inside gets a new number assigned to it. 我希望数字从1开始并递增,因此每个新的Objective和ObjectiveDetail都会获得分配给它的新数字。 I tried to do the following: 我尝试执行以下操作:

     var separator = new[] { " ||| " };
        var objectives = data.Select(s => s.Split(separator, StringSplitOptions.RemoveEmptyEntries))
            .GroupBy(strings => strings[0])
            .Select(grouping, index => new Objective
            {
                Number = grouping.Index,
                Text = grouping.Key,
                ObjectiveDetails = grouping.Select(s, index => new ObjectiveDetail { 
                    Number = index,
                    Text = s[1]
                }).ToList()
            })
            .ToArray();
        return objectives;
    }

This gives me an error on the .Select(grouping, line saying "The name grouping does not exist". Can someone help tell me how I can fix this and add an index to the GroupBy ? 这使我在.Select(grouping,行上显示“名称分组不存在”的错误。有人可以帮我告诉我如何解决此问题并向GroupBy添加索引吗?

我相信您对于具有两个参数的lambda只是语法错误: .Select((groupings, index) => expression)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM