user1926138 user1926138 - 18 days ago 9
ASP.NET (C#) Question

How to get sum of absolute value of columns of data table

I have below code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Data;

namespace Rextester
{
public class Program
{
public static void Main(string[] args)
{
//Your code goes here
DataTable dt = new DataTable();
dt.Columns.Add("Column1");
dt.Columns["Column1"].DataType = typeof(Int32);
dt.Rows.Add(1);
dt.Rows.Add(2);
dt.Rows.Add(-1);
int a = Convert.ToInt32(dt.Compute("SUM(Column1)", "Column1 < 10"));
Console.WriteLine(a);
}
}
}


It will give op as 2, both +ve no will be added and -ve one will be subtracted . I need 4 as OP. I mean abs value of all. How to do it?

Answer

Your question is a bit vague. Imagine that you have

 -20, 1, -2 

In case you want to have 3 == 1 + |-2| (notice that -20 is ruled out and we're filtering by absolute values) you can put Linq which looks quite direct

var result = dt
  .AsEnumerable()
  .Select(record => Math.Abs(Convert.ToInt32(record["Column1"])))
  .Where(item => item < 10)
  .Sum();

In case you want 23 == |-20| + 1 + |-2| (notice that -20 is preserved and we're filtering by values) you can put

var result = dt
  .AsEnumerable()
  .Select(record => Convert.ToInt32(record["Column1"]))
  .Where(item => item < 10)
  .Sum(item => Math.Abs(item));

Edit: in complex queries (see comments below) I suggest using anonymous class:

var result = dt
  .AsEnumerable()
  .Select(record => new {
     Column1 = Convert.ToInt32(record["Column1"]),
     Column2 = Convert.ToString(record["Column2"]) }) 
  .Where(item => item.Column2 == "A" || item.Column2 == "B")
  .Where(item => item.Column1 < 10) 
  .Sum(item => Math.Abs(item.Column1));