c# - Querying a list to find the count of an ID and merge the contents of two similar IDs -
i have generic c# list list<object> results has several fields several rows of data in follows
list<object> results data:
trdid date price seller buyer side 1000 7/23/2015 1 abc null 2 1000 7/23/2015 1 null xyz 1 1002 7/22/2015 1.5 null abc 1 1002 8/22/2015 1.5 null abc 1 1002 7/22/2015 1.5 xyz null 2 1002 8/22/2015 1.5 xyz null 2 1010 8/23/2015 2 acb null 2 1010 8/23/2015 2 null pqr 1 the above list has records ids repeated , want merge records ids repeated twice. , 2 records same ids have same values except seller , buyer seller null when side=1 , buyer null when side=2 , merge them single record replacing null values subsequent other side , resultant list follows
expected results
trdid date price seller buyer 1000 7/23/2015 1 abc xyz 1010 8/23/2015 2 acb pqr as can see above results ids 1000 , 1010 repeated twice, merged each of seller , buyer values , id 1002 discarded count not 2
may know way solve this?
assuming objects in class matching this:
public class result { public int trdid { get; set; } public datetime date { get; set; } public decimal price { get; set; } public string seller { get; set; } public string buyer { get; set; } } then can query list grouping trdid value:
var groupedresults = results .groupby(r => new { r.trdid, r.date, r.price }) .where(g => g.count() == 2) .select(g => new result { trdid = g.key.trdid, date = g.key.date, price = g.key.price, seller = g.first(x => x.seller != null).seller, buyer = g.first(x => x.buyer != null).buyer }); note: need make results variable list<result> work correctly, or use results.cast<result>() first.
Comments
Post a Comment