开发者

Group with LINQ

I have the following data:

CourseID Month  
100      Jan  
100     开发者_运维技巧 Feb  
101      Jan  
102      May  
102      Jun  
102      July  

I would like to write a LINQ query to return the data as follows (including the commas):

CourseID  Months
100       Jan, Feb   
101       Jan  
102       May, Jun, July  

How do I do this?


Try this:

courses.GroupBy(c => c.CourseID)
    .Select(g => new 
    {
        Id = g.Key, 
        Months = String.Join(", ", g.Select(c => c.Month).ToArray()) 
    });

If you're using .NET 4.0 you don't need the ToArray call because String.Join has a new overload to take an IEnumerable.

Explaining how this works:

First you group the set of courses by the CourseID. This will return you an IEnumerable<IGrouping<int, Course>> - each element in the enumerable contains a property called Key - this is the CourseID of all the courses that were grouped into it.

This bit is key: IGrouping is also an IEnumerable<Course> - this means that it can be iterated through returning each of the elements that were grouped under the ID held in Key.

All the last part does is select a new anonymous type with two properties, Id and Months:

  • Id is set to the Key (the CourseID)
  • Months is set to the result of joining together all the Month values for the grouped courses. This is done using String.Join as it makes it easy specify a delimiter for the values.


var q =
    from course in courses
    group course by course.CourseID into courseGroup
    select new
    {
        CourseId = courseGroup.Key, 
        Months = string.Join(", ", (
            from c in courseGroup
            select c.Month).ToArray())
    };


The linq query is rather Straightforward:

var courses = new List<Course>
        {
            new Course(){ CourseId = 100, Month = "JAN"},
            new Course(){ CourseId = 100, Month = "FEB"},
            new Course(){ CourseId = 101, Month = "JAN"},
        };
var q = from course in courses group course by course.CourseId into grouping select new { CourseId = grouping.Key, Months = string.Join(", ", grouping.Select(value => value.Month)) };


The GroupBy() operator should help you get started

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜