【问题标题】:Plain DataSource to Nested Lists c#普通数据源到嵌套列表 c#
【发布时间】:2016-12-01 02:55:29
【问题描述】:

一切都从一个存储过程数据结果开始(简单结构)

IdGrandad、GrandadName、IdDad、DadName、IdChild、ChildName

响应应该是一个嵌套实体列表。


我将数据放入 SqlDataReader... 然后,循环出现了:

var grandadList = new List<Grandad>();

while (reader.Read())
{
    // Properties setters.
    Grandad grandadItem = BindGrandad(reader);
    Dad dadItem = BindDad(reader);
    Child childItem = BindChild(reader);

    // Entities finders.
    Func<Grandad, bool> foundGrandad = (item => item.Identity.Equals(grandadItem.Identity));
    Func<Dad, bool> foundDad = (item => item.Identity.Equals(dadItem.Identity));

    if (!grandadList.Any(foundGrandad))
        grandadList.Add(grandadItem);

    // Here comes the horror-code...
    if (!grandadList.Where(foundGrandad).SelectMany(item => item.DadList).ToList().Any(foundDad))
        grandadList.SingleOrDefault(foundGrandad)?
            .DadList.Add(dadItem);

    grandadList.SingleOrDefault(foundGrandad)?
        .DadList.SingleOrDefault(foundDad)?
        .ChildList.Add(childItem);
}



知道如何简化循环代码吗?

提前致谢!

【问题讨论】:

    标签: c# nested sqldatareader simplify


    【解决方案1】:

    天哪,根本没有答案!

    嗯,我刚刚找到了一个“更好”的解决方案......

    你应该先创建一个普通对象,然后让 .GroupBy() 做 诡计!。

    稍后再读。

    【讨论】:

      猜你喜欢
      • 2012-01-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-06
      • 2020-05-21
      • 2021-05-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多