当值相同时,不执行LINQ求和

时间:2015-09-29 09:45:54

标签: c# linq

我需要从2个LINQ查询开始的sum个相同类型的元素。

以下是我的代码:

        var query1 = from d in _contextProvider.Context.Documents
                     where d.TransportId == transportId
                     group d by d.Type
                     into dg
                     select new { DocumentType = dg.Key.ToString(), DocumentCount = dg.Count() };

        var query2 = from n in _contextProvider.Context.NotificationDocuments
                     where n.TransportId == transportId
                     group n by n.TransportId
                     into nd
                     select new { DocumentType = "Notification", DocumentCount = nd.Count() };

        var query_collapsed = query1.Union(query2)
                    .GroupBy(p => new { DocumentType = p.DocumentType })
                    .Select(g => new DocumentCounters() { DocumentType = g.Key.DocumentType, DocumentCount = g.Sum(p => p.DocumentCount) });

示例:下面让我们分析DocumentType的值等于Notification

query1的值:

enter image description here

query2的值:

enter image description here

折叠查询:

enter image description here

这是正确的:1 + 2 = 3

问题:我注意到,只要query1中Notification的计数等于query2中Notification的计数,就不会执行求和。

示例:

2 + 2 = 2

3 + 3 = 3

有什么想法吗?

1 个答案:

答案 0 :(得分:3)

LINQ Union将删除重复的条目。如果要合并两个序列,可以使用Concat,如下所示:

var query_collapsed = query1.Concat(query2)
                .GroupBy(p => new { DocumentType = p.DocumentType })
                .Select(g => new DocumentCounters() { DocumentType = g.Key.DocumentType, DocumentCount = g.Sum(p => p.DocumentCount) });