我有一个Tag对象:
public class Tag
{
public int TagID { get; set; }
public string Name { get; set; }
public virtual ICollection<Job> Jobs { get; set; }
public Tag()
{
Jobs = new HashSet<Job>();
}
}
并延长:
public class RecentTag : Tag
{
public int Count { get; set; }
}
...我正在尝试从添加到每个对象的查询中使用Count检索RecentTag对象列表:
public IEnumerable<RecentTag> GetRecentTags(int numberofdays)
{
var tags = Jobs
.Where(j => j.DatePosted > DateTime.Now.AddDays(-(numberofdays)))
.SelectMany(j => j.Tags)
.GroupBy(t => t, (k, g) => new
{
RecentTag = k,
Count = g.Count()
})
.OrderByDescending(g => g.Count);
// return RecentTags { TagID, Name, Count, Jobs }
}
那么,如何将查询结果转换为RecentTag类型并返回扩展对象列表?
任何帮助将不胜感激。提前谢谢!
答案 0 :(得分:0)
如果Jobs实际上是Tags的集合,并且它们实际上是RecentTag对象,那么你可以简单地使用Cast方法。
var rtags = tags.Cast<RecentTags>;
但是,如果Jobs不是标签集合,那么您需要投影到RecentTags对象中。
var rtags = tags.Select(x => new RecentTags() { // assign the members });
答案 1 :(得分:0)
我最终做了:
public IEnumerable<RecentTag> GetRecentTags(int numberofdays)
{
DateTime startdate = DateTime.Now.AddDays(-(numberofdays));
IEnumerable<RecentTag> tags = Jobs
.Where(j => j.DatePosted > startdate) // Can't use DateTime.Now.AddDays in Entity query apparently
.SelectMany(j => j.Tags)
.GroupBy(t => t, (k, g) => new RecentTag
{
TagID = k.TagID,
Name = k.Name,
Count = g.Count()
})
.OrderByDescending(g => g.Count)
.Select(a => a);
return tags;
}