Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Skip an empty sequence inside a LINQ .Where statement

I have an array of Tuple arrays like this:

(Type, Func<int, bool>)[][] Formats;

I also have a Type typ and a int i.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading