动态LINQ GROUP BY查询的ASP.NET MVC [英] Dynamic LINQ Group By Query in ASP.NET MVC

查看:876
本文介绍了动态LINQ GROUP BY查询的ASP.NET MVC的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道如何以最佳方式解决这个问题,因为我现在已经在我看来,一个硬codeD柱的伟大工程 - 我不知道我怎么可以扩展它允许列是动态

I'm wondering how to best tackle this, since what I have now works great for a hard-coded column in my view -- I'm wondering how I can extend it to allow the column to be dynamic.

控制器:

var dc = new DataContextDC();
return View(dc.items.Where(i=>i.IsPublic == true));

查看:

<% foreach (var grp in Model.GroupBy(s => s.GroupColumn)) { %>
    <%= Html.Encode(grp.Key) %>
    <% foreach (var item in grp) { %>
        <%= Html.Encode(item.Title) %>
    <% } %>
<% } %>

如前所述,目的是让用户选择哪一列取代GroupColumn上面。我想避免添加任何外部库,等等。

As stated, the objective is to let the user choose which column replaces "GroupColumn" above. I'd like to avoid adding any external libraries, etc.

我看到使用反射(慢,但完全动态的),或者,因为这是一个View在我的应用程序,我只是重复了上述code为数据库中的每个列,然后穿上它一个switch语句(快速,和肮脏的,但有效)

I see using reflection (slow, but fully dynamic) or since this is one View in my application, I just duplicate the above code for each column in the database and then put a switch statement on it (quick, and dirty, but effective)

推荐答案

这是可能是你将要使用的LINQ的<那种事情href="http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx"相对=nofollow>包含在C#中的LINQ样本动态查询库。这样一来,你可以编写查询这样的:

This is probably the kind of thing that you're going to want to use the Linq Dynamic Query library included with the C# Linq samples. That way, you can write the query like this:

var groups = Model.GroupBy("SomeColumn, SomeOtherColumn")

...这是一个伟大的交易更容易,如果你从用户接受列名管理 - 最有可能你已经是列名字符串,该库会自动解析这些出入λEX pressions为您服务。 (您需要捕获 ParseException的如果你希望无效输入的可能性)。

...which is a great deal easier to manage if you're accepting column names from the user - most likely all you have are the column names as strings, and this library will automatically parse those out into lambda expressions for you. (You need to catch ParseException if you expect the possibility of invalid input).

有关格式化密钥,你可能只是其直接传递到 Html.En code 的方法,因为它的默认字符串重新presentation是像 {n = 1,名称=测试} 。如果这是够好,那么我会离开它独自一人,否则你将不得不使用反射来解析出各个关键属性和属性值。

For formatting the key, you can probably just pass it in directly to the Html.Encode method, as its default string representation is something like { ID = 1, Name = Test }. If that's good enough then I would leave it alone, otherwise you'll have to use Reflection to parse out the individual key properties and property values.

编辑:您可以使用图书馆的任何地方,如果你下载这些示例,你会看到,它只是一个源$ C ​​$ C文件

You can use that library anywhere, if you download the samples you'll see that it is just a source code file.

这篇关于动态LINQ GROUP BY查询的ASP.NET MVC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆