简体   繁体   English

带有嵌套 Order By 的 Linq 查询?

[英]Linq query with nested Order By?

Hi there I have the following class structure:嗨,我有以下类结构:

class Apple
{
    public IEnumerable<Banana> Bananas { get; set; }
}

class Banana
{
    public IEnumerable<Carrot> Carrots { get; set; }
}

class Carrot
{
    public DateTime DateCreated { get; set; }
    public IEnumerable<Dog> Dogs { get; set; }
}

class Dog
{
    public string Target { get; set; }
}

I am trying to query all from a collection of Type Apple where Apples.Bananas.Carrots.Dogs.Target matches my input.我正在尝试从 Apples.Bananas.Carrots.Dogs.Target 与我的输入匹配的 Apple 类型集合中查询所有内容。 I currently have.我目前有。

var result = Apples.Where(apple => 
            apple.Bananas.Any(banana => 
                banana.Carrots.Any(carrort => carrort.Dogs.Any(dog => 
                    dog.Target.Equals(input)))));

My difficulty is I now realize I only want the newest entry from the Carrots list.我的困难是我现在意识到我只想要胡萝卜列表中的最新条目。

I have not been able to figure out how to order the carrots by DateCreated descending and take first within this query.我一直无法弄清楚如何按 DateCreated 降序排列胡萝卜,并在此查询中先取。

I have tried the following but its throwing and exception:我尝试了以下但它的抛出和异常:

var result = Apples.Where(apple =>
    apple.Bananas.Any(banana =>
        banana.Carrots.OrderByDescending(carrot =>
            carrot.DateCreated).First().Dogs.Any(dog =>
                dog.Target.Equals(input))));

Exception Exception of type 'Antlr.Runtime.NoViableAltException Exception of type 'Antlr.Runtime.NoViableAltException异常Exception of type 'Antlr.Runtime.NoViableAltException

If you're ever unsure about your LINQ query, by all means, you should simplify it.如果您不确定您的 LINQ 查询,无论如何,您应该简化它。 Remember, LINQ will continue to return IEnumerable until you ask for an object (First, ToArray, ToList, etc.).请记住,LINQ 将继续返回 IEnumerable,直到您请求一个对象(First、ToArray、ToList 等)。 Therefore, there's no harm in simplifying the code in the name of simplicity and debugging.因此,以简单和调试的名义简化代码并没有什么坏处。

var ohGodMyEyes = Apples
   .Where(apple => apple.Bananas
       .Any(banana => banana.Carrots
           .OrderByDescending(carrot => carrot.DateCreated)));

var result = ohGodMyEyes
    .First().Dogs
    .Any(dog => dog.Target.Equals(input));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM