linq union合并子列表

时间:2014-06-16 17:07:55

标签: linq unions

给出一个对象列表如下:

Instance
 - InstanceID

Version
 - VersionID
 - List<Instance> Instances

Activity
 - ActivityID 
 - List<Version> Versions

我想制作一个这样的列表:

Activity
 - ActivityID
 - List<Instance> Instances

目前停留在:

(from activity in activities
 select new {
            activity.ActivityID,
            VersionGroup = (from version in activity.Versions
                            group version by version.ActivityID into versionGroup
                            select versionGroup)
            })

只是不确定如何进入实例级别。

(from activity in activities
 select new { activity.ActivityID,
              Instances = activity.ActivityVersions.SelectMany(v => v.ActivityInstances).AsEnumerable() });

1 个答案:

答案 0 :(得分:5)

您可以使用SelectMany方法展平子列表:

var result = activities.Select(a => new
{
    a.ActivityId, 
    Instances = a.Versions.SelectMany(v => v.Instances)
                          .GroupBy(i => i.InstanceID)
                          .Select(grp => grp.First())
                          .ToList()
});

您可以使用Distinct和自定义IEqualityComparer<Instance>重新组合GroupBy逻辑:

var result = activities.Select(a => new
{
    a.ActivityId, 
    Instances = a.Versions.SelectMany(v => v.Instances)
                          .Distinct(new InstanceComparer())
                          .ToList()
});

class InstanceComparer : IEqualityComparer<Instance>
{

    public bool Equals(Instance x, Instance y)
    {
        return x.InstanceID == y.InstanceID;
    }

    public int GetHashCode(Instance obj)
    {
        return obj.InstanceID.GetHashCode();
    }
}

我还没有完成空检查,但它们是微不足道的。当然,这是假设这是LINQ to Object,因为没有其他标记。