【问题标题】:C#/LINQ to SQL - order combined results from two different result setsC#/LINQ to SQL - 对来自两个不同结果集的组合结果进行排序
【发布时间】:2013-09-23 18:22:29
【问题描述】:

可悲的是,我以前做过。我记得我想通了。今天,我似乎不记得如何做到这一点了。

所以你有这个列表:

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.  
}

上述cmets中的问题。将它们组合在一起后如何订购它们?

【问题讨论】:

  • firstTaters.Concat(secondTaters).OrderBy(d =&gt; d.date_created) .....?
  • 是的,我可以连接(将两个结果加入到一个结果列表中,例如 firstTaters.Concat(secondTaters) 但是然后...我想通过'date_created'对它们进行排序,它们都有字段。

标签: c# linq linq-to-sql concatenation


【解决方案1】:
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&lt;taters&gt;IEnumerable&lt;taters&gt;

【讨论】:

  • 哇——是的!拉姆达声明!!!!不知怎的忘记了。谢谢,谢谢,谢谢!
【解决方案2】:

使用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);

【讨论】:

  • 联盟的优秀点。如果有任何不同的需求,那绝对是好的。谢谢。 Lambda 表达式非常适合 - 谢谢!
【解决方案3】:

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

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();
}

【讨论】:

  • 我想知道这个或 Lambda 表达式是否会做出更快/更有效的选择......
  • 我忘记将 order by 子句放在 to list 语句之前。我喜欢这种方式,因为我可以创建不同的对象提示。当然你也可以用这种方式创建你的taters对象。
【解决方案4】:

只需添加这个:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-19
    • 1970-01-01
    • 2020-06-25
    • 2023-01-21
    • 1970-01-01
    • 1970-01-01
    • 2010-12-22
    • 1970-01-01
    相关资源
    最近更新 更多