views:

34

answers:

3

How to make this method return boolean value, depending on query return. False - nothing, True - data exists. Before i just returned int from uniqueQuote.Count() but does not look like great method. Thank you!

private bool CheckEnquiryUser(int enquiryId, Guid userId)
            {
                int selectedEnquiryId = enquiryId;
                Guid currentUserId = userId;
                Entities ctx3 = new Entities();
                var uniqueQuote = from quot in ctx3.Enquiries.Include("aspnet_Users")
                                  where quot.EnquiryId == selectedEnquiryId &&
                                  quot.aspnet_Users.UserId == currentUserId

                              select quot;

            bool exist = uniqueQuote;
            return exist;
A: 

Try something like:

return uniqueQuote.Count() > 0;
Oskar Kjellin
Never use `.Count() > 0` when you mean `.Any()`; the latter is far more efficient, especially when converted to SQL.
Craig Stuntz
Very true, didn't think of "Any". However .Count > 0 is probably the fastest way if you've allready saved the result in a collection
Oskar Kjellin
Depends on the collection. If it's a linked list, `Count()` will be slower than `Any()`. If it's a `List<T>`, performance should be similar. *However,* `.Any()` will always be more expressive, `Count() > 0` more imperative.
Craig Stuntz
Perhaps performance is similiar. However you said Count() which is not the same as "Count". "Count" is a stored integer and is a lot faster for comparing like 10 > 0 rather than having to start an iteration :)
Oskar Kjellin
`Count()` is the same as `Count` when the underlying type implements `ICollection` http://msdn.microsoft.com/en-us/library/bb535181.aspx So in nearly every instance where there are both `Count` and `Count()`, their performance will be the same.
Craig Stuntz
True, I mean "Count()" for enumerables that does not implenment ICollection.
Oskar Kjellin
For enumerables which *don't* implement `ICollection`, `.Any()` will *always* be more efficient than `.Count > 0`.
Craig Stuntz
Agreed :)......
Oskar Kjellin
+1  A: 

Use the Enumerable.Any method:

return uniqueQuote.Any();

Or pass the predicate to it directly:

return ctx3.Enquiries.Include("aspnet_Users")
           .Any(quot => quot.EnquiryId == selectedEnquiryId
                       && quot.aspnet_Users.UserId == currentUserId);
Ahmad Mageed
+1  A: 

I'm more used to this format, but you can translate to use .Any

return ctx3.Enquiries.Include("aspnet_Users")
     .Any(x=> x.EnquiryId == selectedEnquiryId &&
           x.aspnet_Users.UserId == currentUserId);
Russell Steen