Conditional Group and Select in LINQ with type conversion
I know there is a bunch of questions out there already on this but I still
cannot get it to work due to the type conversion (I think).
I have a list of custom class and I normally group this either by months
(mt) or by quarters (qr) depending on user choice. This works fine.
However, now I have the request to allow grouping by say Q413 and the rest
of 2013 in months. Mt and Qr are strings. Quartpos is a double and equals
4 if only Q4 is in quarters and rest in months.
Here is what I have:
List<MyClass> results = classlist
.GroupBy(a => new {
a.rg,
a.tar,
a.mt = ((double.Parse(a.qr) < quartpos) ? a.mt : 0),
a.qr })
.Select(g => new MyClass {
RG = g.Select(a => a.rg).First(),
tar = g.Select(a => a.tar).First(),
yr = g.Select(a => a.yr).First(),
qr = g.Select(a => a.qr).First(),
mt = g.Select(a => a.mt).First(),
pp = g.Average(a => double.Parse(a.pp)),
pi = g.Sum(a => double.Parse(a.pi)),
cp = g.Average(a => double.Parse(a.cp)),
ci = g.Sum(a => double.Parse(a.ci)),
it = g.Sum(a => double.Parse(a.it)),
to = g.Sum(a => double.Parse(a.to)),
cnt = g.Select(a => a.dt).Distinct().Count(),
pdvol = g.Sum(a => (double.Parse(a.pp) <= 1)
? 0
: (double.Parse(a.pi) /
double.Parse(a.pp))) })
.ToList();
This throws two errors:
String Int type conversion - since mt is string but : 0 is int
Invalid anonymous type member declaration.
I m fully aware that I would have to use the same syntax in the select to
make sure that quarters are selected if grouped by quarters and months if
grouped by mounths also.
Thanks.
No comments:
Post a Comment