简体   繁体   English

Select LINQ的最佳返回类型是什么

[英]what's the best return type for Select LINQ

I'm just getting started with LINQ and C# and I'm unsure what's the recommended return type for a LINQ statement that returns a bunch of records. 我刚开始使用LINQ和C#,并且不确定返回一堆记录的LINQ语句的建议返回类型是什么。

I found the following two notations that work both when linking the data to a gridview. 当将数据链接到gridview时,我发现以下两种表示法均适用。 Which approach should I use in what situation? 在什么情况下应该使用哪种方法?

public object SelectAll()
    {
        var query = from p in dc.Products
                    select new { p.pk_product_id, p.product_name, p.product_price_kg };
        return query;
    }

public IQueryable<Product> SelectAll2()
{
    var query = from p in dc.Products
                select p;
    return query;
}

You don't want to return object . 您不想返回object I wonder where you have seen this. 我想知道你在哪里看到的。
IQueryable<T> or IEnumerable<T> is the preferred way. 首选方法是IQueryable<T>IEnumerable<T>

If this method only gets called as the SelectMethod of a GridView , then it doesn't matter . 如果此方法仅作为GridViewSelectMethod调用,则没关系 The GridView code will be checking at execution time exactly what kind of data it's been given, and deciding what to do with it on the basis of what it is. GridView代码将在执行时准确检查给出的数据类型,并根据数据的性质决定如何处理。 Strong-typing the method doesn't make any difference to the GridView . 强类型化方法不会对GridView造成任何影响。

If you're going to be consuming this method from your own code, then use the most specific type that makes sense. 如果您打算从自己的代码中使用此方法,请使用最有意义的特定类型。

If you are building reusable data access code (and not just a query for a specific form or control) then you should take a look at repository patterns - have a look here . 如果您要构建可重用的数据访问代码(而不仅仅是对特定表单或控件的查询),则应查看存储库模式- 在此处查看

In this case you would want to return strongly typed entities from the query (and not objects from the result of an anonymous class) 在这种情况下,您可能想从查询中返回强类型实体(而不是匿名类结果中的对象)

PS : you can shorten SelectAll2 to PS:您可以将SelectAll2缩短为

return dc.Products.AsQueryable();

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

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