【问题标题】:Linq query to return a flatened list of parent childLinq 查询返回一个扁平化的父子列表
【发布时间】:2008-11-10 11:11:35
【问题描述】:

对 linq 的世界来说还是新手,我需要一些帮助,将有孩子的父母列表扁平化为一个 ParentChild 的列表。

就像这样:

class Program
{
    static void Main()
    {
        List<Parent> parents = new List<Parent>();

        parents.Add(new Parent { Name = "Parent1", Children = new List<Child> { new Child { Name = "Child1" }, new Child { Name = "Child2" } } });
        parents.Add(new Parent { Name = "Parent2", Children = new List<Child> { new Child { Name = "Child3" }, new Child { Name = "Child4" } } });

        // linq query to return List<ParentChild> parentChildList;
        // ParentName = Parent1, ChildName = Child1
        // ParentName = Parent1, ChildName = Child2
        // ParentName = Parent2, ChildName = Child3
        // ParentName = Parent2, ChildName = Child4
    }

    internal class ParentChild
    {
        public string ParentName { get; set; }
        public string ChildName { get; set; }
    }

    internal class Parent
    {
        public string Name { get; set; }
        public List<Child> Children { get; set; }
    }

    internal class Child
    {
        public string Name { get; set; }
    }
}

非常感谢, 克里斯

【问题讨论】:

    标签: c# linq


    【解决方案1】:
    from parent in parents
    from child in parent.Children
    select new ParentChild() { ParentName = parent.Name, ChildName = child.Name };
    

    【讨论】:

    • 如何将它绑定到 Windows 应用程序中的 DataGridView,我已经尝试过 grdTerminals.DataBindings.Add("TerminalName", datasource, "Terminal");但这会返回一个空字符串
    【解决方案2】:

    这应该为你做:

    var k = from p in parents
            from c in p.Children
            select new {Name = p.Name, Child = c.Name };
    

    编辑:Opps 忘记返回一个新的 ParentChild 对象。但肯特打败了我;)

    【讨论】:

      猜你喜欢
      • 2021-11-19
      • 1970-01-01
      • 2010-12-08
      • 2021-07-11
      • 1970-01-01
      • 2021-07-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多