gpt4 book ai didi

linq union合并子列表

转载 作者:行者123 更新时间:2023-12-02 08:33:35 26 4
gpt4 key购买 nike

给定一个对象列表如下:

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

最佳答案

您可以使用 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()
});

您可以将 GroupBy 逻辑替换为 Distinct自定义 IEqualityComparer<Instance> :

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

我还没有做 null 检查,但它们很简单。当然,这是假设这是 LINQ to Object,因为没有其他标记。

关于linq union合并子列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24248765/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com