Click here to Skip to main content
15,887,676 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello Friends,

I am having the table with below structure :

Fruit Name | Is Rotten

Apple - yes
Apple - no
Apple - no
Apple - no
Orange - no
Orange - no
Orange - no
Orange - no
Orange - yes
Orange - yes
Orange - no

I want to group this information and need to form the table with below structure.

Fruit name | no of rotten | total no
Apple - 1 - 4
Orange - 2 - 7

Can you please help me how should I get this group by with the help of SELECT on data table?

What I have tried:

With the help of Select on datatable, we can get group by.
But how to find out the total no of records checked with particular category?
Posted
Updated 24-Apr-18 22:25pm
Comments
CHill60 25-Apr-18 4:17am    
Show the code that you are using up to this point

1 solution

Try this:
C#
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[]
	{
		new DataColumn("Fruit Name", typeof(string)),
		new DataColumn("Is Rotten", typeof(string))		
	});

dt.Rows.Add(new object[]{"Apple", "yes"});
dt.Rows.Add(new object[]{"Apple", "no"});
dt.Rows.Add(new object[]{"Apple", "no"});
dt.Rows.Add(new object[]{"Apple", "no"});
dt.Rows.Add(new object[]{"Orange", "no"});
dt.Rows.Add(new object[]{"Orange", "no"});
dt.Rows.Add(new object[]{"Orange", "no"});
dt.Rows.Add(new object[]{"Orange", "no"});
dt.Rows.Add(new object[]{"Orange", "yes"});
dt.Rows.Add(new object[]{"Orange", "yes"});
dt.Rows.Add(new object[]{"Orange", "no"});

var result = dt.AsEnumerable()
	.GroupBy(x=>x.Field<string>("Fruit Name"))
	.Select(grp=> new
	{
		FruitName = grp.Key,
		NoOfRotten = grp.Count(x=>x.Field<string>("Is Rotten")=="yes"),
		TotalNo = grp.Count()
	})
	.ToList();

Console.WriteLine("{0}\t|\t{1}\t|\t{2}", "FruitName", "NoOfRotten", "TotalNo");
foreach(var r in result)
{
	Console.WriteLine("{0}\t|\t{1}\t|\t{2}", r.FruitName, r.NoOfRotten, r.TotalNo);
}


Result:
FruitName  |  NoOfRotten  |  TotalNo
Apple  |  1  |  4
Orange  |  2  |  7
 
Share this answer
 
Comments
Nibin22 25-Apr-18 4:47am    
Thanks for the answer! It worked nicely!
Maciej Los 25-Apr-18 4:49am    
You're very welcome.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900