C#/LINQ to SQL - 对来自两个不同结果集的组合结果进行排序

本文关键字:结果 两个 排序 组合 SQL to LINQ | 更新日期: 2023-09-27 18:32:24

可悲的是,我以前做过这个。 我记得我想通了这一点。 今天,我似乎不记得该怎么做。

所以你有这个列表:

public List<taters> getTaters(){
    var firstTaters = from s in n.veggies
                      where s.active == true
                     select s.html;
    var secondTaters = from s in n.roots
                      where s.active == true
                     select s.html;
    //now here I want to do something to combine the two 
    //(e.g. a Concat or some such) and   
    //THEN I want to order the concatenated list of results 
    //by 'date_created' descending.  
}

上述评论中的问题。 将它们连接在一起后如何订购它们?

C#/LINQ to SQL - 对来自两个不同结果集的组合结果进行排序

firstTaters.Concat(secondTaters)
           .OrderByDescending(html => html.date_created)

在过滤之前还要尝试在两组上使用串联,以避免代码重复(可能更慢,但更易于维护)

public IEnumerable<taters> getTaters()
{
    return from s in n.veggies.Concat(n.roots)
           where s.active == true
           orderby s.html.date_created descending
           select s.html;
}

不要忘记拨打ToList或更改签名以返回IQueryble<taters>IEnumerable<taters>

使用Concat,或者如果你想要不同的结果,请使用Union

var concated = 
    firstTaters.Concat(secondTaters).OrderByDescending(html => html.date_created);
//Gives distinct values
var unioned = 
    firstTaters.Union(secondTaters).OrderByDescending(html => html.date_created);

或者你可以像下面的例子一样这样做:

public List<taters> getTaters(){
    var firstTaters = from s in n.veggies
                      where s.active == true
                     select s.html;
    var secondTaters = from s in n.roots
                      where s.active == true
                     select s.html;
    return (
        from first in firstTaters
        join second in secondTaters on secondTaters.someField equals second.someField
        select new 
        {
            ....
            ....
        }
    ).toList();
}

只需添加以下内容:

return firstTaters.Concat(secondTaters).OrderByDescending(el => el.DateCreated);