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
// ...