gpt4 book ai didi

c# - 有没有办法使用 LINQ 将重复项目的集合与其子集合合并?

转载 作者:行者123 更新时间:2023-11-30 14:10:09 26 4
gpt4 key购买 nike

示例类:

public class Pallet
{
public int Id { get; set; }
public List<Location> Locations { get; set; }
}

public class Location
{
public int Id { get; set; }
}

鉴于此输入:

var input = new List<Pallet>
{
new Pallet
{
Id = 1,
Locations = new List<Location>
{
new Location { Id = 1 },
new Location { Id = 3 }
}
},
new Pallet
{
Id = 2,
Locations = new List<Location>
{
new Location { Id = 2 }
}
},
new Pallet
{
Id = 1,
Locations = new List<Location>
{
new Location { Id = 1 },
new Location { Id = 4 }
}
},
};

是否有一种很好的 LINQ 方法可以将重复项(在父集合和子集合中)折叠为与此等效的方法?

var output = new List<Pallet>
{
new Pallet
{
Id = 1,
Locations = new List<Location>
{
new Location { Id = 1 },
new Location { Id = 3 },
new Location { Id = 4 }
}
},
new Pallet
{
Id = 2,
Locations = new List<Location>
{
new Location { Id = 2 }
}
}
};

debugger

是的,我可以遍历集合并手动合并项目,但我很好奇 LINQ 是否会/可以提供更具表现力的东西。

最佳答案

您可以使用 GroupBy将匹配的 ID 收集在一起,然后是 Select创建新集合:

var output = input.GroupBy(pallet => pallet.Id)
.Select(grp => new Pallet {
Id = grp.Key,
Locations = grp.SelectMany(pallet => pallet.Locations).Distinct().ToList()
}).ToList();

上面的一个问题是 Distinct() 只有在类类型上才能正常工作,如果你为它提供 IEqualityComparer<Location> ,或者让“位置”类实现 IEquatable<Location> (也覆盖 object.GetHashCode ):

public class Location : IEquatable<Location>
{
public int Id { get; set; }

public bool Equals(Location other)
{
//Check whether the compared object is null.
if (object.ReferenceEquals(other, null)) return false;

//Check whether the compared object references the same data.
if (object.ReferenceEquals(this, other)) return true;

return Id == other.Id;
}

public override int GetHashCode()
{
return Id.GetHashCode();
}
}

或者,您可以只使用第二个 GroupBy 而不是所有的爵士乐在每个组中选择第一个位置:

var output = input.GroupBy(pallet => pallet.Id)
.Select(grp => new Pallet {
Id = grp.Key,
Locations = grp.SelectMany(pallet => pallet.Locations)
.GroupBy(location => location.Id)
.Select(location => location.First())
.ToList()
}).ToList();

关于c# - 有没有办法使用 LINQ 将重复项目的集合与其子集合合并?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25396414/

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