Last active
August 29, 2015 14:09
-
-
Save jrgcubano/901298aed9a91ba118e7 to your computer and use it in GitHub Desktop.
Example SelectMany, Parallell, GroupBy and Select using anonymous objects
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Contract | |
{ | |
public string Code {get; set;} | |
} | |
public class Charge | |
{ | |
public string Name {get; set;} | |
public decimal Total {get; set;} | |
} | |
void Main() | |
{ | |
IList<KeyValuePair<Contract, List<Charge>>> values = new List<KeyValuePair<Contract, List<Charge>>>(); | |
values.Add(new KeyValuePair<Contract, List<Charge>>(new Contract() { Code = "Contract1"}, new List<Charge>() | |
{ | |
new Charge() { Name = "Charge1", Total = 5}, | |
new Charge() { Name = "Charge2", Total = 2} | |
})); | |
values.Add(new KeyValuePair<Contract, List<Charge>>(new Contract() { Code = "Contract1"}, new List<Charge>() | |
{ | |
new Charge() { Name = "Charge1", Total = 5}, | |
new Charge() { Name = "Charge6", Total = 7} | |
})); | |
values.Add(new KeyValuePair<Contract, List<Charge>>(new Contract() { Code = "Contract2"}, new List<Charge>() | |
{ | |
new Charge() { Name = "Charge3", Total = 4}, | |
new Charge() { Name = "Charge4", Total = 3} | |
})); | |
values.Dump(); | |
var singleList = values.AsParallel().SelectMany(x => x.Value.Select(v => new { Contract = x.Key, Charge = v})); | |
singleList.Dump(); | |
var grouped = singleList.GroupBy(x => new { Code = x.Contract.Code, Name = x.Charge.Name }) | |
.Select(s => new { Contract = s.Key.Code, Name = s.Key.Name, Total = s.Sum(i => i.Charge.Total)} ).ToList(); | |
grouped.Dump(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment