0

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);
}
2
  • 2
    I don't follow. Why could docCount be null? Commented Sep 23, 2021 at 17:03
  • 1
    You should not need to. Enumerable.Count might return 0 but it's not going to return null Commented Sep 23, 2021 at 17:03

2 Answers 2

1

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);
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.