[英]Two GroupBy's on LINQ query
Aim : 目的 :
To return an IEnumerable
list of Model
. 返回
IEnumerable
的Model
列表。
Problem : 问题 :
I'm trying to return a list of my model and group on a substring of a field in my database. 我正在尝试在数据库中字段的子字符串上返回模型和组的列表。 However I need to group by twice as the first time I group, the substring has occurred yet and therefore isn't actually grouping on anything as the data is unique before the substring.
但是,我需要进行两次分组,这是我第一次分组时,子字符串尚未出现,因此实际上并没有对任何分组,因为数据在子字符串之前是唯一的。
Edit : 编辑 :
I do not need the first group by. 我不需要第一批。 I am only including it because this was the query before, I am not sure how to do this query.
我只包括它,因为这是之前的查询,我不确定如何执行此查询。 I need to select the nominal period.
我需要选择名义期限。 Get the first four characters of the Nominal Period.
获取标称期间的前四个字符。 Then do a group by on the new 'Nominal Period'
然后根据新的“名义期限”进行分组
Example of a Nominal Period - 201304 标称期间的示例-201304
This is made up of the year and then month. 这是由年份和月份组成。 Ie todays nominal period would be 201509.
即今天的名义期限将是201509。
Therefore whenever I return a Nominal Period with just the first four characters, there will be 12 instances of each nominal period as there are 12 months in the year. 因此,每当我返回仅带前四个字符的标称期时,每个标称期将有12个实例,因为一年中有12个月。 This is why I need to do the second group by.
这就是为什么我需要做第二组。
Model : 型号 :
public class YearsModel {
public string Year { get; set; }
}
View Model : 查看模型 :
public class ReportingHubViewModel : ReportViewModel {
public IEnumerable<YearsModel> Years { get; set; }
public YearsModel YearsModel { get; set; }
}
Controller : 控制器 :
model.Years = detailRepo.GetAllYearsFrom(model.ClientID);
Repository : 仓库 :
public class SQLDetailRepository : IDetailRepository {
ApplicationDbContext camOnlineDb = new ApplicationDbContext();
public IEnumerable<YearsModel> GetAllYearsFrom(int ClientID) {
var x = (from d in camOnlineDb.Details
where d.ClientID == ClientID
where d.NominalPeriod != null
select new {
d.NominalPeriod
});
return x.GroupBy(r => new { r.NominalPeriod })
.Select(g => new YearsModel {
Year = g.Key.NominalPeriod.ToString().Substring(0, 4)
})//Need another group by here to group after the substring has occrured
}
}
You can safely ignore using GroupBy
in this case. 在这种情况下,您可以放心使用
GroupBy
。
One way is to use Distinct()
like following 一种方法是使用
Distinct()
,如下所示
return x.Select(y=>.ToString().Substring(0, 4))
.Distinct()
.Select(z=>new YearsModel {Year = z})
.ToList();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.