3

The following linq

var subjectMarks = (from DataRow row in objDatatable.Rows
                    select Convert.ToDecimal(row["EXM_MARKS"])).Sum();

throws an exception since some row["EXM_MARKS"] has non numeric values like AB etc. How can I get the sum of only numeric ones out of them?

Sнаđошƒаӽ
  • 15,289
  • 12
  • 72
  • 86
Kuntady Nithesh
  • 10,861
  • 17
  • 57
  • 86

6 Answers6

8

Add where clause that filters out the records that cannot be parsed as decimals. Try:

decimal dummy;

var subjectMarks = (from DataRow row in objDatatable.Rows
                     where decimal.TryParse(row["EXM_MARKS"], out dummy)
                     select Convert.ToDecimal(row["EXM_MARKS"])).Sum();
Jakub Konecki
  • 44,908
  • 7
  • 86
  • 126
5

You could create an extension method SafeConvertToDecimal and use this in your LINQ query:

var subjectMarks = (from DataRow row in objDatatable.Rows
                    select row["EXM_MARKS"].SafeConvertToDecimal()).Sum();

This extension method would look like this:

public static decimal SafeConvertToDecimal(this object obj)
{
    decimal result;
    if(!decimal.TryParse(obj.ToString(), out result))
        result = 0;

    return result;
}

This approach has the advantage that it looks clean and you aren't converting each object twice as do all other answers.  

Khalil
  • 939
  • 4
  • 16
  • 33
Daniel Hilgarth
  • 166,158
  • 40
  • 312
  • 426
1

For linq to sql queries you can use built-in SqlFunctions.IsNumeric

Source: SqlFunctions.IsNumeric

irfandar
  • 1,570
  • 19
  • 22
1

use

Decimal Z;

var subjectMarks = (from DataRow row in objDatatable.Rows
                     where Decimal.TryParse (row["EXM_MARKS"], out Z)
                     select Convert.ToDecimal(row["EXM_MARKS"])).Sum();
VdesmedT
  • 8,947
  • 3
  • 33
  • 50
Yahia
  • 68,257
  • 8
  • 107
  • 138
1

You can make some extensions utility class like this for elegant solution:

public static class TypeExtensions
{
    public static bool IsValidDecimal(this string s)
    {
        decimal result;
        return Decimal.TryParse(s, out result);
    }
}

and use it in this way:

var subjectMarks = (from DataRow row in objDatatable.Rows
                     where row["EXM_MARKS"].IsValidDecimal()
                     select Convert.ToDecimal(row["EXM_MARKS"])).Sum();

Hope this helps.

Łukasz Wiatrak
  • 2,727
  • 3
  • 21
  • 37
0
var subjectMarks = objDatatable.Rows.Where(row => row["EXM_MARKS"].ToString().All(char.isDigit))

part of solution is getted in: here

David
  • 6,388
  • 9
  • 30
  • 50