2
\$\begingroup\$

I want to create a ExtensionMethod to ordenate my linq query, called Ordenar. I'll sort it depending what columns is in sortColumns ListDictionary.

I tried some ways, but the best way I arquieve was this :

static class ClienteBusinessExtensions
    {
        public static IQueryable<Model.View_Clientes> Ordernar(this IQueryable<Model.View_Clientes> viewClientes, ListDictionary sortColumns)
        {
            foreach (System.Collections.DictionaryEntry item in sortColumns)
            {
                if (item.Value.ToString()=="ASC")
                {
                    switch (item.Key.ToString())
                    {
                        case "ClienteID":
                            viewClientes = viewClientes.OrderBy(v => v.ClienteID);
                            break;
                        case "Nome":
                            viewClientes = viewClientes.OrderBy(v => v.Nome);
                            break;
                        default:
                            break;
                    }
                }
                else //item.Value.ToString() will be DESC
                {
                    switch (item.Key.ToString())
                    {
                        case "ClienteID":
                            viewClientes = viewClientes.OrderByDescending(v => v.ClienteID);
                            break;
                        case "Nome":
                            viewClientes = viewClientes.OrderByDescending(v => v.Nome);
                            break;
                        case "CpfCnpj":
                            viewClientes = viewClientes.OrderByDescending(v => v.CpfCnpj);
                            break;
                        default:
                            break;
                    }
                }

            }
            return viewClientes;
        }

It is used like this :

var clientesVip = (from vips in db.View_Clientes
                               .Ordernar(sortColumns)
                           select vips);

Are there a clever way to do it? I don't want to use switch statement. I want to sort any field of View_Clientes. It is used in a Asp.NET gridView, when user sort a column.

And View_Clientes entity is :

public partial class View_Clientes
{
    public System.Guid ClienteID { get; set; }
    public string Codcfo { get; set; }
    public string Nome { get; set; }
    public string CpfCnpj { get; set; }
    public string CLI_Origem { get; set; }
}
\$\endgroup\$
1
\$\begingroup\$

You definitely could use DynamicLinq to solve this problem. See Scott Guthries blog post about it at: http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.