Converting LINQ query to Dynamic Linq

c# dynamic-linq linq

Question

I have a function that appears like follows:

public void GetAvailableResourcesByLocationChart(List<DateTime> dates, List<ChartResourceModel> data)
{
    var totals = (from r in data
                  group new { Dates = r.Dates } by r.Location into g
                  select new
                  {
                      Location = g.Key,
                      Dates = dates.Select(d => new
                      {
                          Date = d,
                          Available = g.SelectMany(x => x.Dates.Where(y => y.Date == d)).Count(x => x.Available)
                      })
                      .OrderBy(x => x.Date)
                      .ToList()
                  })
                 .OrderBy(x => x.Location)
                 .ToList();
 }

This illustration organizes the data according to location. However, I would want to be able to put in a string that tells it what to group on. I had assumed DynamicLinq would be the best approach, but I'm having difficulties duplicating it.

I first tried to accomplish this, but I keep getting stuck trying to replicate the SelectMany within the select:

public void GetAvailableResourcesByLocationChart(List<DateTime> dates, List<ChartResourceModel> data, string grouping)
{
    var totals = data.GroupBy(grouping, "it").Select("new (it.Key as Group, it as Dates)").Cast<dynamic>();
}

Any suggestions on what I should do next?

1
0
1/27/2016 7:30:02 PM

Popular Answer

this

   from r in data
   group new { Dates = r.Dates } by r.Location into g
   ...

is equivalent to this

   data.GroupBy(r => r.Location, b => b.Dates)

therefore, if grouper is a variable,

   data.GroupBy(r => {
      if (grouper == "L") 
        return r.Location 
      else
        return r.Dates }, b => b.Dates);

This ought to put you on the right path.

0
1/27/2016 7:36:53 PM


Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow