Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
841 views
in Technique[技术] by (71.8m points)

c# - 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)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...