Use of GroupBy overload method in LinQ

Suppose we have a list of files and our task is to group these file extensions and count the number in each group. For example in below string array you can see we have “.txt” (not case sensative) 4 times, “.pdf” 2 times and “.xml” once.

string[] arr = { “a.txt”, “b.TXT”, “c.pdf”, “d.PDF”, “e.xml”, “f.txt”, “g.txt” };

Logic: To get, the above result we have to first get the extensions of the files and then group them and then count the items in each group. In linq, we have GroupBy extension method that will do this job on behalf of us.

There are two ways of using GroupBy in linq, I’ll show both the ways.

First Method:

string[] arr = { “a.txt”, “b.TXT”, “c.pdf”, “d.PDF”, “e.xml”, “f.txt”, “g.txt” };
var extSet = arr.Select(x => Path.GetExtension(x).ToLower())
.GroupBy(x => x)
.Select(x=> new { Extension = x.Key, Count = x.Count()});
foreach (var item in extSet)
{
Console.WriteLine($”Extension: {item.Extension}, Count: {item.Count}”);
}

 Second Method: GroupBy OverLoad

string[] arr = { “a.txt”, “b.TXT”, “c.pdf”, “d.PDF”, “e.xml”, “f.txt”, “g.txt” };
var extSet = arr.Select(x => Path.GetExtension(x).ToLower())
.GroupBy(x => x, (y, z) => new { Extension = y.Key, Count = z.Count()});
foreach (var item in extSet)
{
Console.WriteLine($”Extension: {item.Extension}, Count: {item.Count}”);
}

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s