user767638
user767638

Reputation:

try parse in linq

Hi I have a linq query as below

var perChange = (from data in globalDS.Tables[0].AsEnumerable().AsParallel()
              select data.Field<double>("PercentChange")).ToList();

Now the dataset globalDS contains null as well as varchar values in them. So there is an obvious type cast error that is generated. Is there a way to try.Parse the value in "Percentage Change" column and select only the valid fields.

Upvotes: 1

Views: 2871

Answers (3)

Tim Schmelter
Tim Schmelter

Reputation: 460380

DataRow.Field supports nullable types:

List<double> result = globalDS.Tables[0].AsEnumerable().AsParallel()
             .Where(r  => r.Field<double?>("PercentChange").HasValue)
             .Select(r => r.Field<double?>("PercentChange").Value)
             .ToList();

Edit: Since you have mentioned that the field contains strings instead of doubles:

List<double> result = globalDS.Tables[0].AsEnumerable().AsParallel()
             .Select(r => r.Field<string>("PercentChange").TryGetDouble())
             .Where(nullDouble => nullDouble.HasValue)
             .Select(nullDouble => nullDouble.Value)
             .ToList();

I've used this extension to try-parse a string to double? which is safer than parsing "on the fly" into the local variable, especially with AsParallel:

public static Double? TryGetDouble(this string item, IFormatProvider formatProvider = null)
{
    if (formatProvider == null) formatProvider = NumberFormatInfo.CurrentInfo;
    Double d = 0d;
    bool success = Double.TryParse(item, NumberStyles.Any, formatProvider, out d);
    if (success)
        return d;
    else
        return null;
}

Upvotes: 4

DjSol
DjSol

Reputation: 208

Try a select using a where clause in which you check the type. This would be something like: where x != null && TypeOf(x) == double

Upvotes: 0

D Stanley
D Stanley

Reputation: 152654

How about this:

double temp;

var perChange = (
     from data in globalDS.Tables[0].AsEnumerable().AsParallel()
     where !data.IsNull("PercentChange")
         && double.TryParse(data.Field<string>("PercentChange"), out temp)
     select double.Parse(data.Field<string>("PercentChange"))
    ).ToList();

Upvotes: 2

Related Questions