Linq 返回包含重复计数的唯一记录



我有一组打印文档:

  • orderDetailId,submittedDate,printedCount
  • 1,1 1月 2106,1
  • 1,1 1月 2106,1
  • 2,3 1月 2106,1
  • 3,5 1月 2106,1
  • 4,6 1月 2106,1

我可以通过以下方式获得所有独特的记录:

private static IQueryable<OrderFields> GetUniqueJobs(IQueryable<OrderFields> jobs)
{
        IQueryable<OrderFields> uniqueJobs = jobs.GroupBy(x => x.OrderDetailId).Select(group => group.First());<br/>
        return uniqueJobs.OrderBy(x => x.SubmittedDate);
}

但我希望字段 printedCount 具有每个文档的打印次数:

  • 1,1 1月 2106,2
  • 2,3 1月 2106,1
  • 3,5 1月 2106,1
  • 4,6 1月 2106,1

我将不胜感激任何帮助

感谢您之前快速的回答,但我没有正确回答问题。我可以用一些缓慢丑陋的代码来说明我想要什么,但这实际上不起作用;-)

private static List<OrderFields> GetUniqueJobs(IQueryable<OrderFields> jobs)
    {
        Guid lastOrderDetailId = Guid.Empty;
        List<OrderFields> uniqueJobs = new List<OrderFields>();
        jobs = jobs.OrderBy(x => x.OrderDetailId);
        foreach (var job in jobs)
        {
            Guid orderDetailId = job.OrderDetailId;
            if (orderDetailId != lastOrderDetailId)
            {
                uniqueJobs.Add(job);
            }
            else
            {
                uniqueJobs[uniqueJobs.Count - 1].Printed++;
            }
        }
        return uniqueJobs;
    }

你能帮忙吗?

试试这个

    var uniqueJobs = jobs.GroupBy(x => new {x.orderDetailId, x.submittedDate})
                         .Select(group => new
                         {
                                orderDetailId = x.Key.orderDetailId,
                                submittedDate = x.Key.submittedDate,
                                printedCount = x.Sum(i => i.printedCount) // Or Count() I dont know your values.
                         });
    return uniqueJobs.OrderBy(x => x.SubmittedDate);
您可以使用

IEnumerable<int,int>>:

private static IEnumerable<KeyValuePair<int,int>> GetUniqueJobs(IQueryable jobs)
{
    var uniqueJobs = jobs.GroupBy(x => x.OrderDetailId).Select(group => new KeyValuePair<int, int>(group.Key, group.Sum(x => x.printedCount))).OrderBy(x => x.Key);
    return uniqueJobs;
}

或者使用匿名类型:

var uniqueJobs = jobs.GroupBy(x => x.OrderDetailId).Select(group => new {OrderDetailId = group.Key, printedCount = group.Sum(x => x.printedCount)});

您可以使用 sum匿名类型来实现它:

var result = jobs.GroupBy(x => x.OrderDetailId)
                 .Select(group => new {
                                          // You can take the first if they are equivalent.
                                          Value = group.First(),
                                          PrintedCount = group.Sum(g => g.PrintedCount)
                                      });

相关内容

  • 没有找到相关文章

最新更新