Search code examples
c#linqc#-3.0aggregateprojection

If I'm projecting with linq and not using a range variable what is the proper syntax?


I have a query that sums and aggregates alot of data something like this:

var anonType = from x in collection
               let Cars = collection.Where(c=>c.Code == "Cars")
               let Trucks = collection.Where(c=>c.Code == "Trucks")
               select new { 
                           Total = collection.Sum(v=>v.Amount),
                           CarValue = Cars.Sum(v=>v.Amout),
                           TruckValue = Trucks.Sum(v=>v.Amount),
                           CarCount = Cars.Count(),
                           TruckCount = Trucks.Count()
               };

I find it really weird that I have to declare the range variable x, especially if I'm not using it. So, am I doing something wrong or is there a different format I should be following?


Solution

  • I could be wrong, but from your usage, I don't think you want to do a traditional query expression syntax query with your collection anyway, as it appears you are only looking for aggregates. The way you have it written, you would be pulling multiple copies of the aggregated data because you're doing it for each of the items in the collection. If you wished, you could split your query like this (sample properties thrown in)

    var values = collection.Where(c => c.Code == "A");
    var anonType = new
                   {
                       Sum = values.Sum(v => v.Amount),
                       MinimumStartDate = values.Min(v => v.StartDate),
                       Count = values.Count()
                   };