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

时间:2016-07-11 12:15:25

标签: linq grouping

我有一系列印刷文件:

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

我可以获得所有独特的记录:

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);
}

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

  • 1,1 Jan 2106,2
  • 2,3 Jan 2106,1
  • 3,5一月2106,1
  • 4月1日,6月2106,

我将不胜感激任何帮助

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

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;
    }

你能帮忙吗?

3 个答案:

答案 0 :(得分:0)

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

if ismember([30 40 50], val)

答案 1 :(得分:0)

试试这个

    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);

答案 2 :(得分:0)

你可以使用IEnumerable&lt; KeyValuePair&lt; INT,INT&GT;&GT;:

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;
}

或使用AnonymusType:

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