What I would like to do is something I find common in MySQL which is to select all of one field distinct, and a sum of another field in that data sub-set for each unique/distinct result.
Following should replicate something simple to use in order to see the type of data I mean :
public class Stock {
public int id {get;set;}
public int count {get;set;}
public string location {get;set;}
public Stock() { }
}
public class Foo {
public void Bar() {
List<Stock> Stocks = new List<Stock>()
{
new Stock
{
id = 137829,
count = 5,
location = "Ottawa"
},
new Stock
{
id = 137829,
count = 27,
location = "Toronto"
},
new Stock
{
id = 137830,
count = 8,
location = "Toronto"
}
};
var result = Stocks.DistincyBy( s => s.id);
}
}
What I would like to store in result
is as follows (using this code as an example. the real project the structure is more complex).
- id = 137829, count = 32
- id = 137830, count = 8
I know I can use .Sum()
, but in this scenario I wish to sum where one field is distinct. How can this be achieved (i prefer my Linq to be inline syntax rather than sql style querying)