简体   繁体   中英

Dynamic LINQ Group By Query in ASP.NET MVC

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.

CONTROLLER:

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

VIEW:

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

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.

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)

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

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

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.

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

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