Linq IEnumerable Select 问题 - 我可以在我的选择中执行所有这些操作吗?
我有一个简短的问题。我可以在 select 语句中执行所有这些逻辑吗?
var entries = atisDAO.GetPME(xl, null);
response.Data.Detectors = new List<DetectorDetails>(entries.Select(pme => new DetectorDetails {ID = pme.PlaceNum.ToString()}));
if(response.Data.Detectors.Any())
{
response.Data.Detectors.ForEach(d =>{
int id;
if(int.TryParse(d.ID, out id))
{
var summaries = atisDAO.GetSummaryEntries(id);
if (summaries.Any())
{
var count = summaries.Sum(summary => summary.TODCount + summary.BFICount + summary.ViolationCount);
var detectionDate = summaries.Max(summary => summary.ReadDate);
d.Count = count.ToString();
d.DetectionTime = new DateTimeZone {
ReadDate = detectionDate.ToString(DATE_FORMAT)
, ReadTime = detectionDate.ToString(TIME_FORMAT)
};
}
}
});
}
进行选择,然后循环列表并修改我刚刚选择的项目感觉不对。我可以在 select 语句中完成所有这些操作吗?
感谢您的任何提示。
干杯,
〜ck在圣地亚哥
I had a quick question. Can I do all of this logic inside the select statement?
var entries = atisDAO.GetPME(xl, null);
response.Data.Detectors = new List<DetectorDetails>(entries.Select(pme => new DetectorDetails {ID = pme.PlaceNum.ToString()}));
if(response.Data.Detectors.Any())
{
response.Data.Detectors.ForEach(d =>{
int id;
if(int.TryParse(d.ID, out id))
{
var summaries = atisDAO.GetSummaryEntries(id);
if (summaries.Any())
{
var count = summaries.Sum(summary => summary.TODCount + summary.BFICount + summary.ViolationCount);
var detectionDate = summaries.Max(summary => summary.ReadDate);
d.Count = count.ToString();
d.DetectionTime = new DateTimeZone {
ReadDate = detectionDate.ToString(DATE_FORMAT)
, ReadTime = detectionDate.ToString(TIME_FORMAT)
};
}
}
});
}
It feels wrong to do a select, then loop through the list and modify the items I just selected. Can I do all of this inside the select statement?
Thanks for any tips.
Cheers,
~ck in San Diego
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
当然可以,为什么不呢?是什么阻止您在 Select 语句中使用 ForEach 中的代码更改新的 DetectorDetails?
Sure, why not? What's stopping you from changing the new DetectorDetails, with the code from the ForEach, in the Select statement?
这有助于您到达目的地吗?我无法确定数据类型是否全部匹配并按原样编译,但这是将所有逻辑放入
.Select()
中的尝试。当然,它还可以增强,变得更好!请随意编辑此答案以使其更好地工作。Does this help get you to where you're going? I can't be sure that the datatypes all match and will compile as-is, but it's a stab at putting all that logic in your
.Select()
. Surely it can be enhanced to be better! Feel free to edit this answer to make it work better.我明白了这一点。我的投影中需要一个 return 语句。
I figured this out. I needed a return statement inside my projection.