I am writing an asp.net web application C#; I have a datatable in memory named " table1" with three columns " country", " productId" and " productQuantity"; I want to expand this table to get a new table (suppose " table2") having the first column " country" as a fixed column and the dynamic number and column names " product_1", " product_2', ...,' product_n'according to the total number of works, existing in ' table1'; the first column " country" should contain the name of the country; dynamically created columns product_1', ' product_2', ..., ' product_n' should contain productQuantity,which was sold for each specific product in the specified country
I use Linq query expressions to write code; the problem is that I cannot hard code the names with the values of the products; I cannot predict how many products exist in a datatable; while I'm testing the results using the following expression:
var query = table1.AsEnumerable()
.GroupBy(c => c.country)
.Select(g => new
{
country = g.Key,
product_1 = g.Where(c => c.productId == "a30-m").Select(c => c.productQuantity).FirstOrDefault(),
product_2 = g.Where(c => c.productId == "q29-s").Select(c => c.productQuantity).FirstOrDefault(),
.
.
.
product_n = g.Where(c => c.productId == "g33-r").Select(c => c.productQuantity).FirstOrDefault()
});
I will give an example of what " table1" looks like and how " table2" should look like this:
see an example of the image of two tables table1 and table2
can someone help me find a solution to create a pivot table with a dynamic column using the linq tree expression or other linq methods; Any help would be greatly appreciated.
source
share