LINQ Learning (6) Group & Join

Source: Internet
Author: User

This article describes the LINQ group and join operations and continues to use the data sources described in the LINQ Learning (3) syntax structure.

Group

Group is a grouping operation, similar to group by in SQL.

The prototype is as follows:

public static IEnumerable<IGrouping<TKey, TSource>> GroupBy<TSource, TKey>(
  this IEnumerable<TSource> source,
  Func<TSource, TKey> keySelector)

It has several overloads, with two types of return: Ienumerable<igrouping<tkey, tsource>>, and ienumerable<tresult>.

The return type is: Ienumerable<igrouping<tkey, tsource>>

Example:

Returns the student's score by school number group

var result = from score in DataSource.Scores
       group score by score.StudentID into scoreGroup
       select scoreGroup;

scoreGroup为IGrouping<TKey, TSource>类型,返回结果为IEnumerable<IGrouping<TKey, TSource>>,既集合的集合,因此输出时需用双重循环。
IGrouping<TKey, TElement>接口定义为:
public interface IGrouping<TKey, TElement> : IEnumerable<TElement>, IEnumerable
{
  TKey Key { get; }
}

Where key is grouped by field.

foreach (var group in result)
{
  //输出分组依据的字段
  Console.WriteLine("\nStudent ID:" + group.Key);
  // 输出组内成员
  foreach (var score in group)
  {
    Console.WriteLine(score);
  }
}
// result:
// Student ID:1
// Student ID:1,Course ID:1,Score:78
// Student ID:1,Course ID:2,Score:60
// ...
// Student ID:2
// Student ID:2,Course ID:1,Score:59
// ...

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.