1

I have a gridview that contains string value but was number/integer

e.g: "1", "10"

problem was I also have data that was - on it and since its a char it cannot convert to integer.

here is a line of my lambda:

var gp_lt = gridData.Where(n => n.Profit != "-" && Convert.ToInt32(n.Profit) >= 0).Select(o => new { o.Profit });
double grossprofit_LT = gp_lt.Sum(o => Convert.ToDouble(o.Profit));

Profit = number but was string ...

value of - was not 0 ... just want to exclude all those who has - and convert the profit to int. Thanks in advance!

Saghir A. Khatri
  • 3,429
  • 6
  • 45
  • 76
Elegiac
  • 361
  • 2
  • 15

2 Answers2

0

Try with:

double grossprofit_LT = gridData.Select(x =>
        {
            var styles = NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint;
            if (x.Profit.StartsWith("-"))
                return (double?) double.Parse(x, styles);

            if (x.Profit.Contains('.'))
                return (double?) double.Parse(x,styles, CultureInfo.InvariantCulture);

            var seperator = CultureInfo.CurrentCulture.NumberFormat.CurrencyDecimalSeparator;

            if (x.Profit.Contains(',') && seperator == ",") 
               return (double?) double.Parse(x, styles);

            return null;
        }).Where(x => x.HasValue).Sum(x => x.Value);

This will handle all values like:

-3
-2.23
1,15

And return you sum of them.If you don't want to include negative numbers just remove the first condition. if (x.Profit.StartsWith("-"))

UPDATE: If you want to make it simpler, and your values doesn't contain any dot or comma, you can just use

gridData.Where(x => !x.Profit.Contains("-"))
        .Select(x => double.Parse(x.Profit.Trim())
        .Sum();

You are comparing Profit with - in your code.But probably some of your values are starts with - so you are getting the format exception.Use Contains or StartsWith method instead.

Selman Genç
  • 100,147
  • 13
  • 119
  • 184
  • whats with the "." and "," – Elegiac Apr 28 '14 at 03:35
  • using .Contains was ok for this condition but i have other lambdas that searching for negative numbers so i cant use .Contains("-") i think ... i just want to exclude the string with exact "-" (dash) value not negative – Elegiac Apr 28 '14 at 03:59
0

Your issue stems from the fact that you have this line in your first statement:

Convert.ToInt32(n.Profit)

That will throw an exception if the string you're trying to convert is not actually an integer. Since you're apparently dealing with profits, you've most likely got decimals.

Replace the above with this, and the code you have should work:

Convert.ToDecimal(n.Profit)

(I'd recommend using Decimal instead of Double when dealing with money.)

Community
  • 1
  • 1
Grant Winney
  • 65,241
  • 13
  • 115
  • 165
  • converting it toDecimal seems work on this condition ... ill just try it on my other lambda and if it works ill accept this answer – Elegiac Apr 28 '14 at 04:12