简体   繁体   English

c# LINQ 到 object 子查询中的自增

[英]c# LINQ to object Autoincrement in subquery

Good Afternoon?下午好? Could anyone suggest how I can implement autoincrement in linq to object subquery which must be started from 1 on every group of main linq query?谁能建议我如何在 linq 到 object 子查询中实现自动增量,该子查询必须从每组主 linq 查询的 1 开始? I have query我有疑问

from student in students
group student by student
into keyStudents
select new StudentClass
{
  Student = keyStudent.Key,
  Subjects = from key in keyStudent
            select new SubjectClass
            {
              Subject = key.Subject,
              SubjectId = (stuck here)
            }
}

My result must be like this:我的结果必须是这样的:

Student
 John
   1. Math
   2. Bio
 Fred
   1. Math
   2. Physics
   3. Bio

My query returns accurate data without SubjectId, but I need to show SubjectId as well.我的查询返回没有 SubjectId 的准确数据,但我还需要显示 SubjectId。 So the SubjectId is just index number started with one in every group.因此,SubjectId 只是每个组中以一个开头的索引号。

You'd have to use method syntax so you can use the override of Select that includes an index您必须使用方法语法,以便可以使用包含索引的Select的覆盖

from student in students
group student by student
into keyStudents
select new StudentClass
{
  Student = keyStudent.Key,
  Subjects = keyStudent.Select((x, i) =>
            new SubjectClass
            {
              Subject = x.Subject,
              SubjectId = i + 1,
            }),
}

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

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