English 中文(简体)
使用类类方法排序查询
原标题:Order a query using a class method
  • 时间:2012-05-23 17:09:49
  •  标签:
  • c#
  • linq

我正试图在上课的班级里 做一个查询订购方法

我写了以下文章, 希望每当我通过一个查询作为参数时,

public static void Ordenar<T>(IEnumerable<T> query, string columna, string orden)
    {
        if (!(String.IsNullOrEmpty(orden) || String.IsNullOrEmpty(columna)))
        {
            if (orden == "ASC") query.OrderBy(x => x.GetType().GetField(columna).GetValue(query));
            if (orden == "DESC") query.OrderByDescending(x => x.GetType().GetField(columna).GetValue(query));
        }
    }

我无法让它像这样运作:

db.Thingys.OrderBy(x=> x.Name);

How can I "select" this field I want to order the query by generically? Please help. D: I m using ASP.NET MVC3

最佳回答

本文中有些内容与您的代码有误,

首先,您需要 return LINQ 查询的结果。 LINQ 运算符不会改变源序列本身 。

其次, columna 参数大概与您序列中的 elements 字段的名称相对应,而不是序列本身。因此,您需要调用通用类型 T 上的 Get ,以及每个元素(指定为 x 参数)上的 GetValue

public static IEnumerable<T> Ordenar<T>(IEnumerable<T> query, 
    string columna, string orden)
{
    if (!(String.IsNullOrEmpty(orden) || String.IsNullOrEmpty(columna)))
    {
        FieldInfo orderField = typeof(T).GetField(columna);

        if (orden == "ASC")
            return query.OrderBy(x => orderField.GetValue(x));

        if (orden == "DESC")
            return query.OrderByDescending(x => orderField.GetValue(x));
    }

    return query;
}
问题回答

查看http://weblogs.asp.net/scottgu/archive/2008/01/07/hird-linq-part-1-using-the-linq-hild-query-library.aspx" rel=“nofollow”>http://weblogs.asp.net/scottgu/archive/2008/01/07/hild-linq-part-1-using-the-linq-hilling-query-library.aspx 用于动态林克的动力-linq-part-1-using-the-linq-hilling-query-library.aspx ,这将允许您根据字符串指定排序和/或过滤(例如用户投入)





相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签