OrderBy使用Dynamic Linq with Relation

时间:2016-12-10 21:51:22

标签: c# asp.net entity-framework linq

我试图通过相关对象的属性进行排序。举个例子,就是这种情况。我有这两个类:

public class Publication
{
    public int Id { get; set; }
    public string Name { get; set; }
    public List<Product> Products { get; set; }
}

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int PublicationId { get; set; }
    [ForeignKey("PublicationId")]
    public Publication Publication { get; set; }
    public int Category { get;set; }
}

现在我需要获得所有出版物的产品类别= 1并按出版物ID desc排序:

IQueryable<Publication> query = db.Publications.Where("Products.Any(Category = 1)");
List<Publication> list = query.OrderBy("Id desc").ToList();

这很棒!但是......如何使用Dynamic Linq按产品类别(desc或asc)订购出版物?

1 个答案:

答案 0 :(得分:0)

我还没有找到使用System.Linq.Dynamic的方法,但至于Linq这是有效的

var query = publications.OrderByDescending(p => p.Products.Select(x => x.Category).FirstOrDefault()).ToList();

这是测试类:

var publications = new List<Publication>
        {
            new Publication
            {
                Products = new List<Product>
                {
                    new Product {Category = 5},
                    new Product {Category = 6},
                    new Product {Category = 7}
                }
            },
            new Publication
            {
                Products = new List<Product>
                {
                    new Product {Category = 2},
                    new Product {Category = 3},
                    new Product {Category = 4}
                }
            },
            new Publication
            {
                Products = new List<Product>
                {
                    new Product {Category = 8},
                    new Product {Category = 9},
                    new Product {Category = 10}
                }
            }
        };

        var query = publications.OrderByDescending(p => p.Products.Select(x => x.Category).FirstOrDefault()).ToList();

        query.ForEach(x => Console.WriteLine(x.ToString()));

输出结果为:

8 , 9 , 10
5 , 6 , 7
2 , 3 , 4

如您所见,它不会在内部订购Products