以下查询返回的类型是什么:
var photos = job.Photos.GroupBy(x => x.Location)
.Select(group =>
new
{
Name = group.Key,
Photos = group.OrderByDescending(x => x.DateAdded)
})
.OrderBy(group => group.Name)
.ToList();
根据调试器,它的类型为:
'System.Collections.Generic.List<<anonymous type: string Name, System.Linq.IOrderedEnumerable<Project.Models.Photo> Photos>>'
但我不知道如何申报此类型。
我已经尝试了
public List<string, IOrderedEnumerable<Photo>> Photos {get; set;)
但List只能采用一个元素
答案 0 :(得分:1)
如果您不想创建另一个类,只需保存此信息,使用Dictionary将字符串键和照片列表保存为值。
IDictionary<string, List<Photo>> photos = job.Photos.GroupBy(x => x.Location)
.Select(group =>
new
{
Name = group.Key,
Photos = group.OrderByDescending(x => x.DateAdded)
})
.OrderBy(group => group.Name)
.ToDictionary(kv=>kv.Name, kv=>kv.Photos.ToList());
答案 1 :(得分:1)
你有几个选择:
Dictionary<TKey, TValue>
使用Value
IOrderedEnumerable<T>
var photos = job.Photos
.GroupBy(x => x.Location)
.ToDictionary(group => group.Key,
group => group.OrderByDescending(x => x.DateAdded));
我会在ToList
之后添加额外的OrderByDescending
来电,以防止只解析和排序一次。
答案 2 :(得分:0)
正如调试器所说,它是匿名类型。这意味着你不能写出它的名字,因为它没有名字。您可以做的是创建一个新类并在查询中使用它:
List<PhotosGroup> photos = job.Photos.GroupBy(x => x.Location)
.Select(group =>
new PhotosGroup
{
Name = group.Key,
Photos = group.OrderByDescending(x => x.DateAdded)
})
.OrderBy(group => group.Name)
.ToList();
或者您可以使用Tuple
类型:
List<Tuple<string, IOrderedEnumerable<Photo>> photos = job.Photos.GroupBy(x => x.Location)
.Select(group =>
Tuple.Create(
group.Key,
group.OrderByDescending(x => x.DateAdded)))
.OrderBy(group => group.Item1)
.ToList();