CatchingMonkey
CatchingMonkey

Reputation: 1391

LINQ Join 2 Datatables and With SUM AND GROUP BY

I simply can not get this to work out at all, so any expert help would be very much appreciated.

I'm trying (as the subject suggests) to join 2 datatables on Zip Code, but return a table which grouped this by State and has a SUM() of sales.

Here's the latest version of my troubles:

var results =(
    from a in dtList.AsEnumerable()
    join b in dtListCoded.AsEnumerable()
    on a.Field<string>("ZIP") equals b.Field<string>("zip") 
    group a by {a.Field<string>("StateCode")} into g
    select new { 
       StateCode = a.Field<string>("StateCode"),
       SumSales = b.Sum(b => b.Field<double>("SUMSales"))
    });

I can join the 2 tables but its getting the result i need that seems to be the tricky bit. If need be I will just have to do 2 queries, but that just seems a bit backward.

Thanks in advance.

Upvotes: 2

Views: 2758

Answers (1)

Kaido
Kaido

Reputation: 3951

Two queries wouldn't be any slower (they should be brought together into a single SQL query upon execution), and would be a lot more readable, transparent during debugging and reusable. I'd recommend breaking it down.

Upvotes: 2

Related Questions