首页 > 解决方案 > 同时迭代两个列表的问题

问题描述

我正在使用 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 是未知的!我感谢任何帮助修复错误。

标签: linqasp.net-core

解决方案


函数中的Numand表示第一个和第二个集合的对象,其中包含,和,和,和对象。 您可以使用and来获取数字,如以下代码:DemNumZipMonthYearTotaltotalMonthYearGrantedCountgrantedCount
total.TotalgrantedCount.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逗号后指定数字。

我希望这可以帮助您解决问题。


推荐阅读