简体   繁体   中英

C#/LINQ to SQL - order combined results from two different result sets

The sad part is, I've done this before. I remember figuring this out. Today, I can't seem to recall how to do this.

So you have this list:

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

Question in above comments. How do I order them AFTER joining them together?

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

also try to use concatenation on two sets before filtering, to avoid code duplication (may be slower, but is more maintainable)

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

Don't forget to call ToList or change signature to return IQueryble<taters> or IEnumerable<taters>

Use Concat , or use Union if you want distinct results

var concated = 
    firstTaters.Concat(secondTaters).OrderByDescending(html => html.date_created);

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

Or you can do this like in the bellow example:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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