简体   繁体   中英

How do I sort a list using LINQ?

I have a LINQ query that populates a list of designers.

Since I am using the filters below my sorting is not functioning the way I want it to.

My question is, given the code below, how can I best sort this List after the fact or sort while querying?

I have tried to sort the list after the fact using the following script but I am receiving a compiler error:

 List<TBLDESIGNER> designers = new List<TBLDESIGNER>();
 designers = 'calls my procedure below and comes back with an unsorted list of designers'
 designers.Sort((x, y) => string.Compare(x.FIRST_NAME, y.LAST_NAME));

My query is as follows:

List<TBLDESIGNER> designer = null;

using (SOAE strikeOffContext = new SOAE())
{
   //Invoke the query
   designer = AdminDelegates.selectDesignerDesigns.Invoke(strikeOffContext).ByActive(active).ByAdmin(admin).ToList();
}

Delegate:

public static Func<SOAE, IQueryable<TBLDESIGNER>> selectDesignerDesigns =
        CompiledQuery.Compile<SOAE, IQueryable<TBLDESIGNER>>(
        (designer) => from c in designer.TBLDESIGNER.Include("TBLDESIGN")
                      orderby c.FIRST_NAME ascending
                      select c);

Filter ByActive:

public static IQueryable<TBLDESIGNER> ByActive(this IQueryable<TBLDESIGNER> qry, bool active)
    {
        //Return the filtered IQueryable object
        return from c in qry
               where c.ACTIVE == active
               select c;

    }

Filter ByAdmin:

public static IQueryable<TBLDESIGNER> ByAdmin(this IQueryable<TBLDESIGNER> qry, bool admin)
{
    //Return the filtered IQueryable object
    return from c in qry
           where c.SITE_ADMIN == admin
           select c;

}

Thanks in advance, Billy

There's a lot going on in your post, but I'm choosing to answer the asked question:

Linq - How to sort a list

Use the declarative OrderBy and ThenBy methods.

designers = designers
  .OrderBy(td => td.FirstName)
  .ThenBy(td => td.LastName)
  .ToList();

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