通过多列返回linq组的类型

时间:2015-03-16 10:10:47

标签: c# linq

我有以下代码:

 var studentClassAttendancesGrouped =
                            classAttendanceByCriteria.OrderBy(x => x.Lecture.Id).GroupBy(x => new { x.Lecture, x.Teacher });

我正在尝试从方法返回studentClassAttendancesGrouped。但我无法确定方法的返回类型。

2 个答案:

答案 0 :(得分:13)

GroupBy

This重叠将从source code返回IEnumerable<IGrouping<TKey, TSource>>

您只需要使用Select()投射您的枚举,当然您必须在最后调用ToList()来执行查询并创建一个列表:

var res = classAttendanceByCriteria.OrderBy(x => x.Lecture.Id)
                                   .GroupBy(x => new { x.Lecture, x.Teacher })
                                   .Select(x => new {x.Key.Lecture, x.Key.Teacher})
                                   .ToList();

但是,上面的代码创建了一个匿名类型列表。如果要从方法返回上述语句,则需要使用或创建自定义对象并返回以下列表:

public class LectureTeacher
{
    public string Lecture { get; set; }
    public string Teacher { get; set; }
}

public List<LectureTeacher> GetDogsWithBreedNames()
{
    var res = classAttendanceByCriteria.OrderBy(x => x.Lecture.Id)
                                       .GroupBy(x => new { x.Lecture, x.Teacher })
                                       .Select(x => new LectureTeacher {Lecture  = x.Key.Lecture, Teacher  = x.Key.Teacher})
                                       .ToList();

    return res;
}

顺便说一句, GroupBy还有其他一些重载,您可以指定结果选择器,它将返回{{1给你:

IEnumerable

答案 1 :(得分:2)

我建议你创建一个自定义类并从你的方法返回它: -

IEnumerable<CustomType> studentClassAttendancesGrouped =
       classAttendanceByCriteria.OrderBy(x => x.Lecture.Id)
       .GroupBy(x => new { x.Lecture, x.Teacher })
      .Select(x => new CustomType { Lecture = x.Key.Lecture, Teacher = x.Key.Teacher });

其中,CustomType看起来像这样: -

public class CustomType 
{
   public string Lecture {get; set; }
   public string Teacher {get; set; }
}

您可以根据需要添加更多列,最后从您的方法返回IEnumerable<CustomType>

因此,您的方法将如下所示: -

public IEnumerable<CustomType> MyMethod()
{
    return classAttendanceByCriteria.OrderBy(x => x.Lecture.Id)
       .GroupBy(x => new { x.Lecture, x.Teacher })
       .Select(x => new CustomType { Lecture = x.Key.Lecture, Teacher = x.Key.Teacher });
}