Simcha Khabinsky
Simcha Khabinsky

Reputation: 2039

Linq-to-SQL ToList() With/without records?

Tried to look for this question on SO, but couldn't find it.

What's the best way to return a list of records from a static method?

I want to return either an empty list or a populated list from my static method.

Given the following method:

    public static List<division> GetAllDivisions(bool isAvailable)
    {
        MyDataContext db = new MyDataContext ();
        List<division> DivisionList = new List<division>();

        var data = from d in db.divisions
                   where d.isAvailable == isAvailable
                   select d;

        if(data.Count() > 0)
            DivisionList = data.ToList();

        return DivisionList;
    }

Do I really need to do the following?

 if(data.Count() > 0)
      DivisionList = data.ToList();

Can I just do DivisionList = data.ToList() without checking the count?

I want to be able to return either a populated list or an empty list - and I don't want an error thrown if there are 0 records.

What are best practices? Is it better to return IEnumerable?

Upvotes: 0

Views: 1075

Answers (1)

Habib
Habib

Reputation: 223422

I want to be able to return either a populated list or an empty list - and I don't want an error thrown if there are 0 records.

You don't have to check for Count, ToList would not return a null, it could return an empty list, which you are trying to do with your check. Simply data.ToList(); is enough. It will return list with records or an empty list, but not null.

You can do:

public static List<division> GetAllDivisions(bool isAvailable)
{
    MyDataContext db = new MyDataContext();
    return db.divisions
             .Where(d => d.isAvailable == isAvailable)
             .ToList();
}

For

Is it better to return IEnumerable?

See: Should I always return IEnumerable<T> instead of IList<T>?

Upvotes: 2

Related Questions