1

可能重复:
从 LINQ 查询返回匿名类型?

我使用这种方法:

public static ... GetList()
    {
        Entity conn = new Entity();
        var lst = (from PS in conn.PurchaserSpecials
                select new
                {
                    PS.PurchaserID,
                    PS.PurchaserSerial,
                    PS.Purchaser.Address,
                    PS.Purchaser.Fax,
                    PS.Purchaser.NumberEconomic
                }).ToList();
return lst;
    }

不能使用 var 作为输出类型。请帮我...

输出方法是什么?

4

4 回答 4

2

它是您创建的匿名类型的列表。

如果您想返回您知道的类型,请创建一个包含您正在选择的字段的新类(我猜下面的类型):

public class Specials
    {
        public int PurchaserID { get; set; }
        public int PurchaserSerial { get; set; }
        public string Address { get; set; }
        public int Fax { get; set; }
        public int NumberEconomic { get; set; }
    }

public static List<Specials> GetList()
    {
        Entity conn = new Entity();
        var lst = (from PS in conn.PurchaserSpecials
                select new Specials
                {
                    PurchaserID =  PS.PurchaserID,
                    PurchaserSerial = PS.PurchaserSerial,
                    Address = PS.Purchaser.Address,
                    Fax = PS.Purchaser.Fax,
                    NumberEconomic = PS.Purchaser.NumberEconomic
                }).ToList();
return lst;
    }
于 2012-07-13T13:16:49.250 回答
1

您的 LINQ 查询生成一个匿名类型,因此不能用作方法的返回类型,调用方法将不知道返回类型的任何信息。

解决此问题的一种方法是使用动态关键字和动态类型。

你方法的返回类型可以是这样的

public dynamic GetList() {
        return ...;
于 2012-07-13T13:18:27.737 回答
0

查询的输出是匿名类型,您不能将其作为参数返回。为了简单起见,最好创建一个类,例如:具有所有这些属性的“PurchaseDetail” ,并返回如下代码:

public static List<PurchaseDetail> GetList() 
    { 
        Entity conn = new Entity(); 
        var lst = (from PS in conn.PurchaserSpecials 
                select new PurchaseDetail
                { 
                    PurchaserID= PS.PurchaserID, 
                    PurchaserSerial=PS.PurchaserSerial, 
                    Address=PS.Purchaser.Address, 
                    Fax=PS.Purchaser.Fax, 
                    NumberEconomic =PS.Purchaser.NumberEconomic 
                }).ToList(); 
return lst; 
    } 
于 2012-07-13T13:21:01.830 回答
0

返回类型将是List of type Products

public static List<Products> GetList()
{
    Entity conn = new Entity();
    var lst = (from PS in conn.PurchaserSpecials
            select new
            {
                PS.PurchaserID,
                PS.PurchaserSerial,
                PS.Purchaser.Address,
                PS.Purchaser.Fax,
                PS.Purchaser.NumberEconomic
            }).ToList();
    return lst;
}

public class Products
{
    //Properties you are using in the query.
}
于 2012-07-13T13:34:56.237 回答