通过查询组合两个LINQ组

时间:2015-03-05 05:14:28

标签: c# .net linq

我通过查询获得了两个LINQ组,我希望首先通过LockAssignment.DateStart组合LockAssignments,然后通过LockAssignment.Lock.Zone组合:

// get the current lock assignments by day for a user
var lockAssignmentByDayForUserQuery = from la in
(
    from la in db.LockAssignment
    select new
    {
      LockAssignment = la,
      UserId = la.UserId,
      DateStart = DbFunctions.TruncateTime(la.DateStart),
      DateExpire = DbFunctions.TruncateTime(la.DateExpire)
    }
)
orderby la.DateStart
group la by la.DateStart into gGroup
select new
{
  DateStart = gGroup.Key,
  LockAssignments = gGroup.Where(q => q.UserId.Equals(userIdForUsername))
};

var lockAssignmentByDayForUser = lockAssignmentByDayForUserQuery.ToArray();

// get the current lock assignments by day for each zone for a user
var lockAssignmentInZoneByDayForUserQuery = from la in
(
    from la in db.LockAssignment
    select new
    {
        LockAssignment = la,
        UserId = la.UserId,
        DateStart = DbFunctions.TruncateTime(la.DateStart),
        DateExpire = DbFunctions.TruncateTime(la.DateExpire)
    }
)
orderby la.DateStart
group la by la.LockAssignment.Lock.Zone.ZoneName into gGroup
select new
{
    Zone = gGroup.Key,
    LockAssignments = gGroup.Where(q => q.UserId.Equals(userIdForUsername))
};

var lockAssignmentInZoneByDayForUser = lockAssignmentInZoneByDayForUserQuery.ToArray();

最终结果如下:

{
    "lockAssignmentInZoneByDayForUser": [
        {
            "DateStart": "2015-03-04T00:00:00",
            "LockAssignments": [
                {
                    "Zone": "Watches",
                    "LockAssignmentDetails": {}
                },
                {
                    "Zone": "Jewlery",
                    "LockAssignmentDetails": {}
                }
            ]
        },
        {
            "DateStart": "2015-03-05T00:00:00",
            "LockAssignments": [
                {
                    "Zone": "Jewlery",
                    "LockAssignmentDetails": {}
                }
            ]
        }
    ]
}

任何帮助都会很棒!提前谢谢!

1 个答案:

答案 0 :(得分:0)

您可以使用以下内容。它没有经过测试,因为我没有数据结构。

db.LockAssignment.OrderBy(la => la.DateStart)
                 .GroupBy(la => la.DateStart).Select(datedGroup => new
                 {
                   DateStart = datedGroup.Key,
                   LockAssignments = datedGroup.GroupBy(la => la.Zone, grp => new { Zone = grp.Zone, Details = datedGroup.Select(result => result) })
                 });