In
this post I’ll explain how one can group data using LINQ GroupBy. GroupBy can
be applied on different data types like Generic List, XML, DataTable etc.
Syntax of Group By:
var result= from c in <collection>
group c by c.<property> into
g
select new
{
Key=g.Key,
Value=g
};
|
LINQ
Grouping return partitioned sets of data from a collection based on a given key
value, i.e. group employees by designation as:
var query = from c in employees
group
c by c.Designation;
//or same statement can be written in Lambda expression as:
var query = employees.GroupBy(c => c.Designation);
|
GroupBy Result: Let’s understand result returned by
LINQ grouping operation.
The
return collection from a GroupBy is:
IEnumerable<IGrouping<TKey, TElement>>;
The
IGrouping interface inherits from IEnumerable<TElement> and has a read
only key property of type TKey.
public interface IGrouping<TKey, TElmt> : IEnumerable<TElmt>
{
TKey Key { get;
}
}
|
Few points to
consider:
·
LINQ
grouping operation result is an enumerable sequence of groups with each group
having a distinct key value
·
The
key value is determined by the key selection expression that equates the key
value for each element
Example of GroupBy:
//empmployee designations.
var empDesignations = new
string[]
{
"Manager",
"Senior
Associate",
"Associate",
"Senior
Associate",
"Jr.
Associate",
"Associate",
"Senior
Associate",
"Associate"
};
//Group By using LINQ
Console.WriteLine("---------------
Using Plain LINQ ---------------");
(from ed in
empDesignations
group ed by ed
into
g
select
new
{
Key = g.Key,
Count = g.Count()
})
.ToList()
.ForEach(c => Console.WriteLine("Number of {0} is {1}", c.Key,
c.Count));
//Group By using LINQ Lambda
Console.WriteLine("---------------
Using Lambda LINQ --------------");
empDesignations
.GroupBy(g => g)
.Select(c => new
{ Key = c.Key, Count = c.Count() })
.ToList()
.ForEach(c => Console.WriteLine("Number of {0} is {1}", c.Key,
c.Count));
|
Comments
Post a Comment