如何GROUPBY使用动态LINQ使用 [英] How to use GroupBy using Dynamic LINQ
问题描述
我试图做一个GROUPBY使用动态LINQ,但有麻烦它的工作。
I am trying to do a GroupBy using Dynamic LINQ but have trouble getting it to work.
这是说明问题的一些示例代码:
This is some sample code illustrating the problem:
List<dtoMyAlbum> listAlbums = new List<dtoMyAlbum>();
for (int i = 0; i < 5000; i++)
{
dtoMyAlbum album = new dtoMyAlbum
{
Author = "My Author",
BookID = i,
CurrSymbol = "USD",
Price = 23.23,
Shop = i % 3 == 0 ? "TESCO" : "HMV"
};
listAlbums.Add(album);
}
IQueryable<dtoMyAlbum> mydata = listAlbums.AsQueryable();
int count = mydata.Count();
//var mydataGrouped = mydata.GroupBy(a => a.Shop); // <-- this works well (but is not dynamic....)
var mydataGrouped = mydata.GroupBy("Shop"); // <-- does not compile but is kind of what I want...
foreach (var group in mydataGrouped)
{
//count = group.Count();
}
我意识到我缺少了elementSelector在GROUPBY超载,但所有我想做的是(在这种情况下)两套dtoMyAlbum的对象,所以我想选择所有集合的所有元素...
I realise that I am missing the 'elementSelector' in the GroupBy overload but all I want to do is to end up with (in this case) two sets of dtoMyAlbum objects so I wish to select ALL elements for all sets...
我怎么会落得去呢?
推荐答案
有是默认的是
定义,你可以用它来返回匹配的元素:
There is default it
defined, you can use it to return matched elements:
var mydataGrouped = mydata.GroupBy("Shop", "it");
要通过结果迭代还应额外选择
元素命名,并使用动态
取值:
To iterate through results you should additionally Select
elements to name it and use dynamic
s:
var mydataGrouped = mydata.GroupBy("Shop", "it").Select("new (it.Key as Shop, it as Albums)");
foreach (dynamic group in mydataGrouped)
{
foreach (dynamic album in group.Albums)
{
Console.WriteLine(album.Author);
}
}
这篇关于如何GROUPBY使用动态LINQ使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!