How to use TryParse in linq where

918 Views Asked by At
        else{ 
            if(a.Item2 == ">"){
                    result = dict.Where(x => x.Value.Any(y => y.Key == a.Item1 && double.TryParse(y.Value,out double res) == double.TryParse(a.Item3,out double res1)));
                //result = dict.Where(x => x.Value.Any(y => y.Key == a.Item1 && Convert.ToDouble(y.Value) > Convert.ToDouble(a.Item3)));    
            }
            else if(a.Item2 == "<")
                result = dict.Where(x => x.Value.Any(y => y.Key == a.Item1 && Convert.ToDouble(y.Value) < Convert.ToDouble(a.Item3)));
            else if(a.Item2 == "<=")
                result = dict.Where(x => x.Value.Any(y => y.Key == a.Item1 && Convert.ToDouble(y.Value) <= Convert.ToDouble(a.Item3)));
            else if(a.Item2 == ">=")
                result = dict.Where(x => x.Value.Any(y => y.Key == a.Item1 && Convert.ToDouble(y.Value) >= Convert.ToDouble(a.Item3)));
            else if(a.Item2 == "==")
                result = dict.Where(x => x.Value.Any(y => y.Key == a.Item1 && Convert.ToDouble(y.Value) == Convert.ToDouble(a.Item3)));
            else if(a.Item2 == "!=")
                result = dict.Where(x => x.Value.Any(y => y.Key == a.Item1 && Convert.ToDouble(y.Value) != Convert.ToDouble(a.Item3)));
            else
                 throw new Exception("Comparison operator not found");          
        }

How can i use double.TryParse in the above code situation inplace of Convert.ToDouble as i dont know how to use the out value for the comparison. I want to use TryParse because I'm getting the following error message :

input string was not in a correct format

How i can achive this in the current senario?

1

There are 1 best solutions below

0
On BEST ANSWER

It gets a little long-winded, but assuming you want to only return the rows where the values can be parsed to a double:

result = dict.Where(x => x.Value.Any(y => y.Key == a.Item1 
     && double.TryParse(y.Value,out double res)  // Value can be parsed
     && double.TryParse(a.Item3,out double res1) // Item3 can be parsed
     && res == res1)); // the 2 parsed results match