Get those elements from a List of custom class objects whose one property value is parseable to double

I have a list of custom class objects in C# with class structure like this:

public class ABC
{
   int ID;
   string Text1;
   string Text2;
}

This list stores data like this:

+-----+-------+--------+
| ID  | Text1 |  Text2 |
+----------------------+
| 1   | PQR   |  test1 |
|     |       |        |
| 2   | XYZ   |  12.69 |
+-----+-------+--------+

I am trying to get rows with distinct ID like this:

ABCObject = ABCObject.GroupBy(c => c.ID).Select(c => c.First()).ToList();

It's working fine. But, I want to add another condition that ABCObject should contain only those rows that have double data. In above given case it's row with ID = 2. So, is it possible to do this in LINQ? Or I have to create another function that will run a foreach loop and test each element using double.TryParse()?

Jon Skeet
people
quotationmark

You can use double.TryParse within LINQ, although admittedly the out parameter is annoying:

ABCObject = ABCObject
    .Where(x => { double ignored; return double.TryParse(x => x.Text2, out ignored); }
    .GroupBy(c => c.ID)
    .Select(c => c.First())
    .ToList();

You could make this cleaner with your own reusable method which uses nullable types instead of bool+out to return the result:

private static double? NullableTryParseDouble(string text)
{
    double result;
    return double.TryParse(text, out result) ? result : default(double?);
}

Then:

ABCObject = ABCObject
    .Where(x => NullableTryParseDouble(x.Text2) != null)
    .GroupBy(c => c.ID)
    .Select(c => c.First())
    .ToList();

people

See more on this question at Stackoverflow