title: Linq/EF Dynamic Group by with optional parameter
body: <p>I'm facing a problem with my search/group function.</p>
  
  <p><strong>Context</strong></p>
  
  <p>I've a list of customer objects (Entity Framework Context) and I want to find all possible duplicates in this list. The criteria if an object is a duplicate should be dynamic. Let's say selectable by the UI.</p>
  
  <p><strong>Model</strong></p>
  
  <p>Let's assume the following parts as given.</p>
  
  <p>My CustomerClass</p>
  
  <pre><code>public class Customer
  {
      public int CustomerId { get; set; }
      public string SearchName { get; set; }
      public string Mail { get; set; }
      public DateTime? Birthday { get; set; }
      public string CardNumber { get; set; }
      public DateTime Created { get; set; }
  }
  </code></pre>
  
  <p>Possible criteria for duplicates are: SearchName, Mail, Birthday and CardNumber.</p>
  
  <p>The following function returns an appropriate result:</p>
  
  <pre><code>    public IList&lt;Customer&gt; GetPossibleDuplicates()
      {
          IList&lt;Customer&gt; list;
  
          list =
              (from s in this.Context.Customers
                  group s by new
                             {
                                 s.SearchName, 
                                 s.CardNumber
                             }
                  into g where g.Count() &gt; 1 select g)
                  .SelectMany(g =&gt; g)
                  .OrderBy(o =&gt; o.SearchName)
                  .ThenBy(c =&gt; c.Created)
                  .ToList();
  
  
          return list;
      }
  </code></pre>
  
  <p>The problem I've is to make the group by statement "dynamic" so based on the selected creteria the grouping is made. Any suggestions for a good solution?</p>