简体   繁体   English

Linq-to-SQL ToList()有/没有记录?

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

Tried to look for this question on SO, but couldn't find it. 试图在SO上寻找此问题,但找不到它。

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? 我可以不进行计数就做DivisionList = data.ToList()吗?

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. 我希望能够返回填充列表或空列表- 并且我不希望在有0条记录的情况下引发错误。

What are best practices? 什么是最佳做法? Is it better to return IEnumerable ? 返回IEnumerable更好吗?

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. 我希望能够返回填充列表或空列表-并且我不希望在有0条记录的情况下引发错误。

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. 您不必检查CountToList不会返回null ,它可以返回一个空列表,您正在尝试进行检查。 Simply data.ToList(); 只是data.ToList(); is enough. 足够。 It will return list with records or an empty list, but not null. 它将返回带有记录的列表或一个空列表,但不为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? 返回IEnumerable是否更好?

See: Should I always return IEnumerable<T> instead of IList<T>? 请参阅: 我是否应该始终返回IEnumerable <T>而不是IList <T>?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM