Help understanding how to organize and sum data (in DataTables)? How do I LINQ?

Hopefully this is the right place to ask this; if there is a place for more beginner-level questions, as this may be, please let me know. I am still trying to wrap my head around LINQ and anonymous types, and I think that's what this issue is. The bottom line is that I don't know how to group and organize and sum data, especially given the need for conditionals.

Here is a very basic example DataTable:

Item Type Buy Price Sell Price Market
Game 10 15 eBay
Game 5 10 Amazon
Book 2 5 eBay
Book 3 5 Amazon
Book 4 5 Amazon
Furniture 25 50 Amazon

If I were working with this example I would be trying to get:

  1. The total count for each Item Type for each market
  2. The sum Buy Price and Sell Price for each Item Type in each market

Using my example:

Item Type eBay Item Total Amazon Item Total eBay Sold Total Amazon Sold Total
Game 1 1 15 10
Book 1 2 5 10
Furniture 0 1 0 50

The Total Items part seems simple enough to me, and getting the sum of the Sell Price would be possible for me if I didn't need that extra conditional…

var itemTypes = from item in itemTable group item by item.Field<string>("Item Type") into type select new { type = item.Field<string>("Item Type"), ebayItems = item.Count(i => i.Field<string>("Market") == "eBay"), amazonItems = item.Count(i => i.Field<string>("Market") == "Amazon"), ebaySold = item.Sum(i => i.Field<int>("Sell Price") if i.Field<string>("Market") == "eBay") // this obviously doesn't work! } 

I think this betrays my lack of understanding about how to deal with data using LINQ and groups. I am probably going about doing this the wrong way. Perhaps I should just be looping through the items in the DataTable… I've been thrust into this C# situation and can't seem to find a great beginner's breakdown of even the distinction between doing something like (from x group x.y into g) and x.GroupBy(x => x.y) or how to work with groups once they've been created.

Any help would be immensely appreciated! Thank you so much.

by OzzyHere via /r/csharp

Leave a Reply