I have one data table/ excel in which there are lots of columns, first column is id and one of the columns is Amount, and that amount is filled with values. I want to sum up the amount of the rows whose ID are duplicate , and in result data table all non duplicate rows also should be there
we wold recommend to recheck the above requirement part
dictLK | Dictionary (Of String, Int32) =
(From d in YourDataTable.AsEnumerable
Group d by k=d("id").toString.Trim into grp=Group
Let cn = grp.Sum(Function (g) CInt(g("sum").toString.Trim))
Select t = Tuple.Create(k,cn)).ToDictionary(Function (t) t.Item1, Function (t) t.Item2)
Step 2: Assign dtResults = (From row In Dt.AsEnumerable
Group row By col1=row(0).ToString.Trim Into grp = Group
Select dtResults.Rows.Add({col1, grp.Sum(Function (x) CInt(x(1).toString.Trim))})).CopyToDataTable
This will work even unique value exists in the datatable.
hello darshan, my column index in not fix, can you please make it by ID and SUM name so that if my index changes the it can process data by column names
Step 2: Assign dtResults = (From row In Dt.AsEnumerable
Group row By col1=row(“ID”).ToString.Trim Into grp = Group
Select dtResults.Rows.Add({col1, grp.Sum(Function (x) CInt(x(“Sum”).toString.Trim))})).CopyToDataTable
( From row In dt.AsEnumerable
Group row By k=row("id").ToString.Trim
Into grp=Group
Let cs = grp.Sum(Function(x) CDbl(x("Sum").ToString))
Select dt2.Rows.Add({k, cs.ToString})
).CopyToDataTable
I have given it as per the structure you have show …if there are more column add those details in {k, cs.ToString} like grp.First()("ColumnName").ToString in the same order you need
var query = from row in originalDataTable.AsEnumerable()
group row by row.Field(“id”) into grp
select new
{
id = grp.Key,
sum = grp.Sum(r => r.Field(“Amount”))
};
DataTable resultDataTable = new DataTable();
resultDataTable.Columns.Add(“id”, typeof(int));
resultDataTable.Columns.Add(“sum”, typeof(int));
foreach (var item in query)
{
resultDataTable.Rows.Add(item.id, item.sum);
}