我如何从中得到:
var props = new List<RoomProperties>();
props.Add(new RoomProperties(new[] {3, 4, 5}, new string[] {"AC", "WC"}));
props.Add(new RoomProperties(new[] {2}, new string[] {"AC", "TV"}));
props.Add(new RoomProperties(new[] {3}, new string[] {"Music", "Phone"}));
对此:
Key = 2, Values = ("AC", "TV")
Key = 3, Values = ("AC", "WC","Music", "Phone" )
Key = 4, Values = ("AC", "WC")
Key = 5, Values = ("AC", "WC")
使用props.props.SelectMany()
我可以让键变平,但值与之无关。如果您有一个好主意如何以优雅的方式做到这一点我会很感激。
基本上我希望每个ID连接房间属性,ID用这些数据唯一表示。
private class RoomProperties
{
public readonly int[] RoomIds;
public string[] Properties { get; private set; }
public RoomProperties(int[] roomIds, string[] properties)
{
RoomIds = roomIds;
Properties = properties;
}
}
答案 0 :(得分:2)
您可以使用房间ID和房间属性将序列展平为匿名对象。然后按房间ID对这些对象进行分组,并从组中选择所有属性(我还添加了Distinct以避免重复的房间值):
props.SelectMany(p => p.RoomIds.Select(id => new { id, p.Properties }))
.GroupBy(x => x.id)
.Select(g => new {
g.Key,
Values = g.SelectMany(x => x.Properties).Distinct()
});