linq - 同时迭代两个列表的问题
问题描述
我正在使用 ASP.NET Core 3.1。我已经编写了一些类似下面的代码,现在我想获得这两个具有相同大小的查询的结果并遍历它们中的每一个并划分它们的元素并将结果存储在一个列表中。但现在问题出在我的 zip 方法中,我无法准确指定要划分的每个查询的哪个属性。
var mytotal = _context.Apiapp.GroupBy(o => new
{
Month = o.ApiRequestDate.Substring(4, 2),
Year = o.ApiRequestDate.Substring(0, 4)
}).Select(g => new
{
Month = g.Key.Month,
Year = g.Key.Year,
Total = g.Count()
}).OrderByDescending(a => a.Year).ThenByDescending(a => a.Month).ToList();
var numerator = from t1 in _context.Apiapp
join t2 in _context.ApiAppHistory on t1.Id equals t2.ApiApplicantId
join t3 in _context.EntityType on t2.LastReqStatus equals t3.Id
where t1.IsDeleted == false && t1.LastRequestStatus == t2.Id && t3.Name == "granted"
group new { Year = t1.ApiRequestDate.Substring(0, 4), Month = t1.ApiRequestDate.Substring(4, 2) }
by new { t2.LastReqStatus } into g
select new
{
Year = g.Max(n => n.Year),
Month = g.Max(n => n.Month),
GrantedCount = g.Count()
};
var GrantedReqStatus = numerator.ToList();
var GrantedAccessPercent = new List<Double>();
//-------------------------------------------------------
var res = mytotal.Zip(GrantedReqStatus, (total, GrantedCount) => new { Num = total, Denum = GrantedCount });
foreach(var r in res)
{
GrantedAccessPercent.Add(r.Num/r.Denum);
}
在 foreach 的内部,r.Num 和 r.Denum 是未知的!我感谢任何帮助修复错误。
解决方案
函数中的Num
and表示第一个和第二个集合的对象,其中包含,和,和,和对象。
您可以使用and来获取数字,如以下代码:DemNum
Zip
Month
Year
Total
total
Month
Year
GrantedCount
grantedCount
total.Total
grantedCount.GrantedCount
var res = mytotal.Zip(GrantedReqStatus, (total, grantedCount) => new { Num = total.Total, Denum = grantedCount.GrantedCount });
foreach(var r in res)
{
GrantedAccessPercent.Add(Math.Round(r.Num / (double)r.DemNum, 2));
}
请注意,要进行除法,int1/int2
您需要强制int2
转换为double
,将给出预期的结果,您也可以使用Math.Round
逗号后指定数字。
我希望这可以帮助您解决问题。
推荐阅读
- c++ - 在arduino上显示输入数据的大小和整数的输入数据
- c# - 将 Json 数据传输到 C# 列表
- github - Github Pages 仅在某些目录中找不到 index.html
- prolog - 如何获取用户输入的每个单词的首字母
- mongodb - 我无法使用 Visual Studio Code 将 Strapi 与 MongoDB 连接起来。请协助我
- html - 如何修改里面的内容
- java - 类和子类之间的隐式和显式转换
- c - 如果一个变量是一个结构体的指针,那么通过指针变量访问结构体数据成员的操作符是什么?
- php - 替换单词并保持找到的字符串区分大小写
- sql - 如何识别两行数据的所有匹配列?