James Wilson
James Wilson

Reputation: 5150

Simple LINQ count, or so I thought

I am trying to get a count of this:

Model.Version.Where(model => model.revision != Model.revision).Count();

However it tells me in VS that I cannot use Lambda expressions.

The model is of type Documents, which is keyed to Version.

I need the count of any documents in the version table for the model documents where the revision is greater than the model revision.

This will either be a 0 or a 1, could sometimes be higher than 1 I suppose.

What am I doing wrong?

if (Model.Version.Where(model => model.revision > Model.revision).Count() > 0)
{
     // do something
}

Upvotes: 1

Views: 132

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500055

As others have said, your real code should be fine: it sounds like the problem was only that you were trying to execute this in the debugger instead of in normal code. Personally I'm always somewhat leery of trying to take things too far in the debugger - it can be useful of course, but if things behave unexpectedly, I'd always see whether the same code works as part of a real program, rather than assuming there's something fundamentally wrong with the approach. The debugger has to work under rather different constraints than the normal compilation and execution process.

Likewise, as others have said, it's better to use Any() than Count() > 0. However, cleaner yet is to use the overload of Any accepting a predicate:

if (Model.Version.Any(model => model.revision > Model.revision))
{
    ...
}

Note however that that's not quite the same as your initial predicate, which was asking for any versions which had a different revision rather than a higher revision. You may want:

if (Model.Version.Any(model => model.revision != Model.revision))
{
    ...
}

It's worth noting that in LINQ to Objects, using Any can have very real performance benefits over using Count() > 0. In providers which convert the query to a different form (e.g. SQL) there may be no performance benefit, but there's a clarity benefit in saying exactly what you're interested in - you don't really care about the count, you only care if there are any matching items.

Upvotes: 7

Related Questions