使用LINQ在列表中对列表进行聚合

时间:2016-01-13 15:39:16

标签: c# mongodb linq

作为this question的后续,我需要在MongoDB中聚合内部数组,我试图在LINQ中完成相同的任务。

我很接近,因为我已经想出如何聚合一个单独的项目:

// Get collection
var collection = _database.GetCollection<VehicleDataUpload>("Vehicles");

// Get first project that meets our identifier
var firstProject = collection.AsQueryable().Where(i => i.ProjectId.Equals("1234")).First();

// Get a list of DailySummaryData objects 
var aggregation = 
    from entry in firstProject.VehicleEntries
    group entry by entry.Data
    into result
    select new DailySummaryData() {
        ProjectName = firstProject.ProjectId,
        Date = result.FirstOrDefault().Date,
        Passed = result.Sum(x => (x.VehicleStatus.Equals("PASSED") ? 1 : 0)),
        Failed = result.Sum(x => (x.VehicleStatus.Equals("FAILED") ? 1 : 0))
    };

return aggregation.ToList();

但是,我不能在集合上使用...First(),因为项目可能有多个VehicleDataUpload。如何聚合返回的文档列表中的所有列表?

1 个答案:

答案 0 :(得分:1)

尝试以下内容:

// Get collection
var collection = _database.GetCollection<VehicleDataUpload>("Vehicles");

// Get first project that meets our identifier
var aggregation = collection
    .AsQueryable()
    // This will return an IEnumerable of Vehicles object
    .Where(i => i.ProjectId.Equals("1234"))
    // Assuming you want to return a plain list, you should use SelectMany
    .SelectMany(v => v.VehicleEntries
        // You group each list of VehicleEntries
        .GroupBy(ve => ve.Data)
        // For each group you return a new DailySummaryData object
        .Select(g => new DailySummaryData() {
            ProjectName = v.ProjectId,
            Date = g.Key,
            Passed = g.Sum(x => (x.VehicleStatus.Equals("PASSED") ? 1 : 0)),
            Failed = g.Sum(x => (x.VehicleStatus.Equals("FAILED") ? 1 : 0))
        })

return aggregation.ToList();