Linq动态排序子属性

时间:2014-01-09 17:48:04

标签: sorting datatable linq-to-entities

基于this示例,我可以将排序应用于父记录属性。但是,我无法对子记录应用排序。

在该示例中,创建了一个委托,用于设置公司属性的排序:

Func<Company, string> orderingFunction = (c =>  sortColumnIndex == 1 ? c.Name :
                                                sortColumnIndex == 2 ? c.Address :
                                                c.Town);

然后应用于结果集:

results = results.OrderBy(orderingFunction)

现在,假设公司有子记录,我将如何使用相同的技术对子属性进行排序?

我试过这样的事情:

Func<ChildObject, string> orderingFunction = (c => c.ChildRecords.FirstOrDefault().SomeProperty );

我尝试将排序直接应用于结果集:

results = results.OrderBy(x => x.ChildRecords.OrderBy(c => c.SomeProperty))

这两种方法都不奏效。

1 个答案:

答案 0 :(得分:1)

首先,它为什么不起作用的原因

Func<ChildObject, string> orderingFunction = (c => c.ChildRecords.FirstOrDefault().SomeProperty );

此代码无效,因为它只接受一个子记录。

results = results.OrderBy(x => x.ChildRecords.OrderBy(c =>
        c.SomeProperty)) 

这不起作用,因为无论您是通过子记录订购,默认情况下都会根据x条件对其进行排序。

那么,如何使其有效? 如果您想订购公司列表,只需将逻辑排序放在订购功能中即可。这样的事情。

    results = results.OrderBy(Function(m)
  If "Check custom logic to determine the order" Then
      Return 2
  Else
      Return 1
  End If
 End Function)

它是基于VB.NET语言的。为此道歉。我不确定C#中的语法,但这个想法大致是这样的。

对于示例案例,类结构如下:

            Parent p1 = new Parent
            {
                Name = "Test1",
                Index = "1",
                Children = new List<Child> { 
                    new Child {Name = "Child1", Index = "3"},
                    new Child {Name = "Child2", Index = "2"},
                    new Child {Name = "Child3", Index = "1"}
                }
            };

            Parent p2 = new Parent
            {
                Name = "Test2",
                Index = "2",
                Children = new List<Child> { 
                    new Child {Name = "Child4", Index = "6"},
                    new Child {Name = "Child5", Index = "5"},
                    new Child {Name = "Child6", Index = "4"}
                }
            };

            List<Parent> listParent = new List<Parent>();
            listParent.Add(p1);
            listParent.Add(p2);

那么,您想要实现的是对所选的Child属性进行排序?

我假设这样的事情?这可以根据孩子订购。

listParent.ForEach(x => {
    x.Children = x.Children.OrderBy(y => y.Index).ToList();
});
listParent.ToList<Parent>().ForEach(x => x.Children.ToList<Child>().ForEach(y => Console.WriteLine(y.Name)));