如何进行分组时如何向LINQ查询添加索引?

时间:2013-08-06 03:20:04

标签: c# linq

我有以下可用的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;
    }

我想要做的是在Objective中填充一个名为Number的字段 对象和ObjectiveDetail对象中名为Number的字段。我想要 数字从一开始并递增,因此每个新的Objective和ObjectiveDetail inside获取分配给它的新编号。我试着做以下事情:

     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;
    }

这给了我一个关于.Select的错误(分组,行说“名称分组不存在”。有人可以帮我告诉我如何解决这个问题并为GroupBy添加索引吗?

1 个答案:

答案 0 :(得分:1)

我相信你的语法错误,因为lambda有两个参数:.Select((groupings, index) => expression)