1

I have function that return all clients in database it is looks like this:

MyContext db = new MyContext();
db.Configuration.LazyLoadingEnabled = false;
db.Configuration.ProxyCreationEnabled = false;
var clients = db.clients.???;

My question is how can I return all clients if exists and if not null(similar to first or default somthing like all or default)?

ilay zeidman
  • 2,654
  • 5
  • 23
  • 45

2 Answers2

2

In my opinion you should return an empty IEnumerable and not null when there are no clients.

But if you insist, you can do the following:

var clients = db.clients.AsEnumerable();

return clients.Any() ? clients : null;

If this is something you plan on doing it a lot, you could make it into an extension method like this:

public static class DbExtensions
{
    public static IEnumerable<T> ManyOrNull<T>(this IEnumerable<T> elements)
    {
        return elements.Any() ? elements: null;
    }
}

Then in your other method you could just write:

return db.clients.ManyOrNull();
Klaus Byskov Pedersen
  • 117,245
  • 29
  • 183
  • 222
2

Have a try.

var hasClients = db.clients.Any();
if (hasClients)
{
   //TODO: If exist;
   var list = db.clients.ToList();
}
else
{
   //Default: Null
} 
spajce
  • 7,044
  • 5
  • 29
  • 44
  • it is also solution but @Klaus Byskov Pedersen work for me first so I give him the answer thank you! – ilay zeidman Feb 02 '14 at 13:01
  • 2
    take note that [.Any() and .Count()](http://stackoverflow.com/questions/305092/which-method-performs-better-any-vs-count-0) had a big difference in terms of checking a value if exist. – spajce Feb 02 '14 at 13:03
  • but if I do have clients does any will return those client or it returns bool? because I want to return all client if there exists clients – ilay zeidman Feb 02 '14 at 13:07