【问题标题】:Projecting aggregated data to flat one将聚合数据投影到平面
【发布时间】:2014-03-28 21:25:24
【问题描述】:

我如何从中得到:

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

【问题讨论】:

  • 显示您的RoomProperties 课程。
  • 完全不清楚RoomProperties 的样子。不清楚Music 和Phone 从你的结果中去哪里了。不清楚您的预期结果是什么

标签: c# linq join flatten


【解决方案1】:

您可以将序列展平为具有房间 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() 
     });

【讨论】:

  • 这很快:) 很好。我没有想到你可以简单地在 SelectMany 中使用匿名。谢谢
  • 真的是一个关于 LINQ 强大功能的好例子!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-10-06
  • 2023-03-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-10
  • 1970-01-01
相关资源
最近更新 更多