Home > OS >  How to combine LINQ Query with a Null check
How to combine LINQ Query with a Null check

Time:09-24

Is it possible to combine these LINQ queries? I if so would it make it harder to read.

docCount = dbContext.Documents.Count(x => x.DocumentRequest.Id == Id);
if (docCount == null)
{
   docCount = dbContext.Documents.Count(x => x.DocumentRequest.Guid == Guid);
}

CodePudding user response:

Attempting to combine these would be highly inefficient as it would result in a O(N^2) complexity.

Your approach would work fine if you change the null check to check for a 0 integer instead as the return value can't be null since int is a value type.

Try this:

docCount = dbContext.Documents.Count(x => x.DocumentRequest.Id == Id);
if (docCount == 0)
   docCount = dbContext.Documents.Count(x => x.DocumentRequest.Guid == Guid);

CodePudding user response:

As other stated, this should be a 0 check. Now, if your question is "can I avoid to do 2 enumeration if I end up in the second case", the answer is yes:

(int idCount, int guidCount) = dbContext.Documents.Aggregate((0, 0), ((int id, int guid) acc, Document doc)
  => (acc.id   (doc.Id == id ? 1 : 0), acc.guid   (doc.Guid == guid ? 1 : 0)));
docCount = idCount != 0 ? idCount : guidCount;

which only iterates the documents once.

Is this more readable? ... no. Slightly more performant and readable:

int idCount = 0;
int guidCount = 0;
foreach (var document in dbContext.Documents)
{
    if (document.Id == id)
        idCount  ;

    if (document.Guid == guid)
        guidCount  ;
}
docCount = idCount != 0 ? idCount : guidCount;

Is it worth it? It depends of your data. If enumerating your documents is a hot path that you have identified after proper benchmarking and is the best improvement you can make in your codebase/architecture (for example, hundred of millions of documents on a distant database, with no copy on local program, and this count is run often), then yes.

Otherwise, this is premature optimization, stick with your solution, with 0 instead of null.

  • Related