LINQ dynamic group on demand in ASP.NET MVC

I am wondering how best to solve this, because what works fine for my hard-coded column in my view now - I wonder how I can expand 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 indicated, the goal is to allow the user to choose which column replaces the "GroupColumn" above. I would like not to add external libraries, etc.

I see the use of reflection (slow but completely 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 the switch statement on it (fast and dirty, but efficient)

+3
2

, , Linq Dynamic Query, # Linq, , :

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

..., , - , , , - , - , ( ParseException, ).

Html.Encode, - - { ID = 1, Name = Test }. , , Reflection .

: , , , .

+4

Source: https://habr.com/ru/post/1737019/


All Articles