AspdotnetCodes.com
Search
Articles
Books
Resources
Asp.Net News
Downloads
Free Tech Magazines
Asp.Net Web Hosting
Archives
Softwares
Newsletter
Suggest Us
Link to Us
Feeds Subscription
Articles
Questions & Answers
Tips & Tricks
 How to Group Multiple DataTable Columns through LINQ to DataSet (C#)?
Posted by Moderator1 on  9/17/2015 9:45:52 AM 1311 Views
One day, I want to group a DataTable with multiple columns. As I don’t want to do this another SQL Statement, I want to try with the traditional way in LINQ to DataSet. But the result is not what I expect. Even though all the records are of same values, the columns are not grouped. So, I provide the correct syntax of grouping the DataTable through LINQ to DataSet concept below in both C#.

DataTable dt = new DataTable();
dt.Columns.Add("ProductName");
dt.Columns.Add("ProductCategory");
dt.Columns.Add("ProductSubCategory");
dt.Columns.Add("ProductPrice", System.Type.GetType("System.Decimal"));

DataRow dr1 = dt.NewRow();
dr1["ProductName"] = "Skirt Red";
dr1["ProductCategory"] = "Female";
dr1["ProductSubCategory"] = "Kids";
dr1["ProductPrice"] = 19;
dt.Rows.Add(dr1);

DataRow dr2 = dt.NewRow();
dr2["ProductName"] = "Jeans Blue";
dr2["ProductCategory"] = "Male";
dr2["ProductSubCategory"] = "Kids";
dr2["ProductPrice"] = 25;
dt.Rows.Add(dr2);

DataRow dr3 = dt.NewRow();
dr3["ProductName"] = "Jeans Black";
dr3["ProductCategory"] = "Male";
dr3["ProductSubCategory"] = "Adult";
dr3["ProductPrice"] = 25;
dt.Rows.Add(dr3);

DataRow dr4 = dt.NewRow();
dr4["ProductName"] = "Jeans Black";
dr4["ProductCategory"] = "Male";
dr4["ProductSubCategory"] = "Adult";
dr4["ProductPrice"] = 25;
dt.Rows.Add(dr4);

var newGroup = (from row in dt.AsEnumerable()
group row by new
{
ProductCategory = row.Field<string>("ProductCategory"),
ProductSubCategory = row.Field<string>("ProductSubCategory")
} into grp
select new
{
ProductSubCategory = grp.Key.ProductSubCategory,
ProductCategory = grp.Key.ProductCategory,
TotalPrice = grp.Sum(r => r.Field<Decimal>("ProductPrice"))
});

foreach (var item in newGroup)
{
Response.Write(item.ProductCategory + " | " + item.ProductSubCategory + " | " + item.TotalPrice.ToString() + "<br/>");
}

Post New Tips/Tricks View all Tips/Tricks

Featured Resources:
Many .NET teams are underperforming, is yours?
Explore how you can turn your .NET developer training program from a commonly ignored budget line-item into a strategic weapon in today's competitive software environment.
Simply SQL - Free 111 Page Preview!
Simply SQL is a practical step-by-step guide to writing SQL.
100% Free Subscription until Stock lost.View complete list.
Sponsored by