??? GetProductByGroup()
{
var q = from p in db.Products
group p by p.CategoryID into g
select new { CategoryID = g.Key, g };
return q;
}
如上面的查询,我根据分类ID:CategoryID进行分类,然后返回结果。那么这个返回值类型该写什么呢?
{
var q = from p in db.Products
group p by p.CategoryID into g
select new { CategoryID = g.Key, g };
return q;
}
如上面的查询,我根据分类ID:CategoryID进行分类,然后返回结果。那么这个返回值类型该写什么呢?
解决方案 »
- gridview分页时的问题
- 【ActiveReport】未处理的System.NullReferenceException类型的异常出现在未知模块中【在线+急!】
- 在数据绑定时,如何"用列专用的文本代替空值"
- 上传控件!当选择好图片时,同时应该显示出来,然后看是否保存到数据库?
- 两问(SQL更新日期及获取来访页面URL)
- 救急,怎么才能在线编辑WORD文件!!
- dropdownlist和textbox绑定的问题
- ASP.NET中如何得到硬盘的序列号的引用问题?
- 请问谁能告诉我一下如何将 Web程序 嵌入游戏客户端
- 谁有实现连动下拉框的源代码,给我一个,我是菜鸟嘛,把剩下的分都跟您了!
- 数据库问题
- 索引超出范围。必须为非负值并小于集合大小。参数名: index(三层)
即便返回IEnumerable非泛型,外边也无法识别里边的元素类型
Products GetProductByGroup()
{
Products q = from p in db.Products
group p by p.CategoryID into g
select new Products
{
CategoryID = g.Key,
Count=g.Count()
};
return q;
}
foreach (dynamic item in list)
{
}但是dynamic非常损耗性能,建议先建一个实体来做组成list
List<Product> productList=from p in db.Products
group p by p.CategoryID into g
select new Product { CategoryID = g.Key, g };
return productList;
从语义上,{ CategoryID = g.Key, g }是一个全新的匿名类,和现有的Product 是不同的。
从语义上,{ CategoryID = g.Key, g }是一个全新的匿名类,和现有的Product 是不同的。
你既然要这样定义一个函数,就不能使用匿名类了。
http://msdn.microsoft.com/en-us/library/bb397696.aspx
select new { CategoryID = g.Key, g }
明显就不是Products!不信,你自己编译下看。
下面是我的测试代码,works well.
假设Product定义如下:
class Product
{
public int CategoryID{set;get;}
public string Description { set; get; }
public int ProductID { set; get; }
}你的函数可以写成这样
IEnumerable<IGrouping<int, Product>> GetProductByGroup(List<Product> products)
{
return products.GroupBy(p => p.CategoryID);
}测试代码:List<Product> products = new List<Product>() {
new Product(){CategoryID = 1, Description="1 description", ProductID = 1},
new Product(){CategoryID = 2, Description="2description", ProductID = 2},
new Product(){CategoryID = 2, Description="3description", ProductID = 3},
new Product(){CategoryID = 3, Description="4description", ProductID = 4},
new Product(){CategoryID = 3, Description="5description", ProductID = 5},
new Product(){CategoryID = 3, Description="6description", ProductID = 6}, }; foreach (IGrouping<int, Product> g in GetProductByGroup(products))
{
Console.WriteLine(g.Key);
foreach (Product p in g)
{
Console.WriteLine(p.Description);
}
}