Question

I'm trying to convert query of queries used in ColdFusion to LINQ and C#. The data come from data files, rather than from the database.

I converted the first query, but have no clue as to

  1. how to use it to query the second query.

  2. how to include count(PDate) as DayCount in the second query.

Below is the code using query of queries in ColdFusion:

First query
<cfquery name="qSorted" dbtype = "query">
    SELECT OA, CD,PDate,
    FROM dataQuery 
    GROUP BY CD,OA,PDate,       
</cfquery>

Second query
<cfquery name="qDayCount" dbtype = "query">
    SELECT OA, CD, count(PDate) as DayCount 
    FROM qSorted   // qSorted is from the first query.            
    GROUP BY 
    OA, CD
    ORDER BY 
    OA, CD
</cfquery>

Here's the first converted LINQ query, and it works fine:

var Rows = allData.SelectMany(u => u._rows.Select(t => new
{          
  OA = t[4],
  CD = t[5],
  PDate = t[0]              
}))
.GroupBy(x => new { x.CD, x.OA, x.PDate  })
.Select(g => new
{
  g.Key.OA,
  g.Key.CD,
  g.Key.PDate 
})
.ToList();

Here's the pseudo-code for the second LINQ query, which I need your assistance:

var RowsDayCount  = Rows //Is this correct? If not, how to do it?
.GroupBy(x => new { x.OA, x.PDate, x.CD, })
.Select(g => new
{
  g.Key.OA,
  g.Key.CD,
  g.Key.PDate,//PDate should be PDate.Distinct().Count() asDayCount    
  // See DayCount in cfquery name="qDayCount" above.
})
.OrderBy(u => u.OA)
.ThenBy(u => u.CD) 
.ToList();
Était-ce utile?

La solution

Your second query origionally wasn't grouping on PDate, but your translation is. That's wrong. If you want to count the number of PDates for each OA/CD pair, you need to not group on PDate. Once you've made that change, you can modify the Select to pull out all of the PDate values from the group, and count the distinct values.

.GroupBy(x => new { x.OA, x.CD, })
.Select(g => new
{
    g.Key.OA,
    g.Key.CD,
    DayCount = g.Select(item => item.PDate).Distinct().Count(),
})
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top