I'm trying to search in an IEnumerable
for a specific record (using a predicate). If that record doesn't exist, I want to return the first record. If that also doesn't exist, I just want null
.
I'm currently using
var category = categories.FirstOrDefault(
c => c.Category == "C") ??
category.FirstOrDefault();
ReSharper gives me a warning (Possible multiple enumeration of IEnumerable). The warning tells me my sql statement might be executed twice. Once to try and find a "C" category, and once more to get the first record. The warning will go away if I first convert categories to a List by using categories.ToList()
. But if categories contains a lot of records, that could be slow.
Is there a more elegant way to do this? Or should I just ignore the warning?
IEnumerable
in code, I'd suggest a custom extension method; but given that these items are from a SQL server, if you want to do it without always iterating all records, you need to do it on the database server. I'd consider it unlikely that there's a set of LINQ methods that could be automatically translated, so a sproc would be my suggestion. – AakashM