I have an array of Tuple arrays like this:
(Type, Func<int, bool>)[][] Formats;
I also have a Type typ and a int i.
I then need an IEnumerable<(Type, Func<int,bool>[])> (aka return items) where a potential match is evaluated by Item1 (i.e. Type) matching typ in the format .IsAssignableFrom(typ). If we get a match, then we aren’t done: we only include it if Item2.Invoke(i) evaluates to true.
var results = Formats.Where(f => f.Where(o => o.Item1.IsAssignableFrom(typ)).First().Item2.Invoke(i));
This is not valid because I think if a return item doesn’t have an inner item to retrieve in the .First() call, it throws an InvalidOperationException "Sequence contains no data" because you can’t call .First() on an empty sequence.
Can you help restate this Linq to ignore the sequence if empty?
>Solution :
This is a perfect opportunity to use the Enumerable.FirstOrDefault() method:
Returns the first element of a sequence, or a default value if no element is found.
In this case, the "default value" would be (null, null). So, use FirstOrDefault() instead of First(), and then ignore items appropriately. Something like this might work:
var results = Formats.Where(f => f.Where(o => o.Item1.IsAssignableFrom(typ)).FirstOrDefault().Item2?.Invoke(i) ?? false);