Nis*_*dru 10 c# linq anonymous-types
嗨,我需要找到一种方法来声明一个方法的匿名类型.这是我的代码:
public List<var> ListOfProducts(string subcategory)
{
var products = (from p in dataContext.Products
join s in dataContext.SubCategories.Where(x => x.SubCatName == subcategory)
on p.SubcatId equals s.SubCatId
join b in dataContext.Brands on p.BrandId equals b.BrandId
select new
{
Subcategory = s.SubCatName,
Brand = b.BrandName,
p.ProductName,
p.ProductPrice
});
return products;
}
Run Code Online (Sandbox Code Playgroud)
我不知道我应该为该方法设置List的类型.在这种情况下我该怎么办?
Dav*_*ych 21
您无法Anonymous Type
从方法返回.
只需为您的类型创建一个类并返回该类.
public class Product
{
string Subcategory { get; set; }
string Brand { get; set; }
string ProductName { get; set; }
decimal ProductPrice { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
然后返回:
var products = (from p in dataContext.Products
join s in dataContext.SubCategories.Where(x => x.SubCatName == subcategory) on p.SubcatId
equals s.SubCatId
join b in dataContext.Brands on p.BrandId equals b.BrandId
select new Product
{
Subcategory = s.SubCatName,
Brand = b.BrandName,
p.ProductName,
p.ProductPrice
});
return products;
Run Code Online (Sandbox Code Playgroud)
编辑:为了澄清我首先声明,如@JamesMichaelHare指出,在技术上有可能通过返回返回从一个方法匿名类型object
或dynamic
,但它可能是更多的麻烦比它的价值,因为你不得不使用Reflection
或某种其他方式访问对象的属性.
根据MSDN,动态类型使其发生的操作能够绕过编译时类型检查.相反,这些操作在运行时解决.
所以试试这个:
public IEnumerable<dynamic> ListOfProducts(string subcategory)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
7225 次 |
最近记录: |