Note that there are some explanatory texts on larger screens.

plurals
  1. POConstruct a LINQ GroupBy query using expression trees
    primarykey
    data
    text
    <p>I have stuck on this problem for a week and no solution found.</p> <p>I have a POCO like below:</p> <pre class="lang-cs prettyprint-override"><code>public class Journal { public int Id { get; set; } public string AuthorName { get; set; } public string Category { get; set; } public DateTime CreatedAt { get; set; } } </code></pre> <p>I want to know during a specific date span ( grouped by months or years ) the amount of journals count by a AuthorName or a Category.</p> <p>After I send the queryed object to JSON serializer then generated JSON data like below ( just using JSON to demonstrate the data I want to get, how to serializer a object to a JSON is not my problem )</p> <pre><code>data: { '201301': { 'Alex': 10, 'James': 20 }, '201302': { 'Alex': 1, 'Jessica': 9 } } </code></pre> <p>OR</p> <pre><code>data: { '2012': { 'C#': 230 'VB.NET': 120, 'LINQ': 97 }, '2013': { 'C#': 115 'VB.NET': 29, 'LINQ': 36 } } </code></pre> <p>What I know is to write a LINQ query in "method way" like:</p> <pre class="lang-cs prettyprint-override"><code>IQueryable&lt;Journal&gt; query = db.GroupBy(x=&gt; new { Year = key.CreatedAt.Year, Month = key.CreatedAt.Month }, prj =&gt; prj.AuthorName) .Select(data =&gt; new { Key = data.Key.Year * 100 + data.Key.Month, // very ugly code, I know Details = data.GroupBy(y =&gt; y).Select(z =&gt; new { z.Key, Count = z.Count() }) }); </code></pre> <p>The conditions that grouped by months or years, AuthorName or Category will be passed by two string type method parameters. What I don't know is how to use "Magic String" parameters in a GroupBy() method . After some googling, it seems that I cannot group data by passing a magic string like "AuthorName". What I should to do is build a expression tree and pass it to the GroupBy() method.</p> <p>Any solution or suggestion is appreciate.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload