0

Those are my classes:

List<MyDate> Dates

public class MyDate
{
    public DateTime FromDate { get; set; }
    public List<Tuple<DateTime, List<MyEnum>>> ToDates { get; set; }
}

I'm trying to retrieve the nearest FromDate property to a originDate, but I need it to do the comparison only for items that answer the statement of Where(d => d.ToDates.Any(t => t.Item2.Contains(MyEnum.Value1)))

long nearestDiff = myList
            .Where(d => d.ToDates.Any(t => t.Item2.Contains(MyEnum.Value1)))
            .Select(d => d.FromDate)
            .Min(date => Math.Abs((date - originDate).Ticks));

The problem is when none of the items is answering the Where statement the Select statement throw the exception of:

System.InvalidOperationException: 'Sequence contains no elements'

I tried using the SingleOrDefault as this answer suggested, but I need the Min value will be calculated against all values not only a single one.

Shahar Shokrani
  • 7,598
  • 9
  • 48
  • 91
  • 2
    I doubt Select is throwing this exception. What makes you believe it is Select which throws? Have you checked the stacktrace of the exception? Also, what precisely is `myList` (what type)? –  Feb 17 '19 at 13:06
  • `Select` isn't throwing the exception, `Min` is. And the answer to which you linked **does not** suggest that you use `SingleOrDefault` in place of `Min`. – David Feb 17 '19 at 13:09

0 Answers0