Below is my code in which I am trying to copy 3 Columns "BATCH NUM", "QTY" and "PROD ID" from one to another. Problem is that "BATCH NUM", "QTY" are copied but "PROD ID" column is not copied.
var newDt = dt.AsEnumerable()
.GroupBy(r => r.Field<string>("BATCH NUM"))
.Select(g =>
{
var row = dt.NewRow();
row["BATCH NUM"] = g.Key;
row["QTY"] = g.Sum(r => Convert.ToInt32(r.Field<string>("QTY")) + Convert.ToInt32(r.Field<string>("BONUS")));
row["PROD ID"] = g.Select(r => r.Field<string>("PROD ID"));
return row;
}).CopyToDataTable();
How can I copy "PROD ID" to DataTable?
Using Select
on PROD ID
means you are trying to store collection of string in a column which supports storing a string value. This will by default calls ToString method on a collection and results in System.Linq... string value in a column.
You want to use appropriate function to get all values in the column:
var newDt = dt.AsEnumerable()
.GroupBy(r => r.Field<string>("BATCH NUM"))
.Select(g =>
{
var row = dt.NewRow();
row["BATCH NUM"] = g.Key;
row["QTY"] = g.Sum(r => Convert.ToInt32(r.Field<string>("QTY")) + Convert.ToInt32(r.Field<string>("BONUS")));
row["PROD ID"] = String.Join(",", g.Select(x => x.Field<string>("PROD ID")).Distinct());
return row;
}).CopyToDataTable();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.