C# LINQ - sort and group a Dictionary<string,DateTime> by date with maximum group size -
i looking created batches dictionary<string, datetime>
following constraints:
- all items in batch share same date
- there can no more x items in single batch. if there more items same date, batch must created.
i have worked out following logic, wondering if there other more succinct way of doing linq.
using system; using system.collections.generic; using system.linq; using system.text; namespace dictionary_sort_by_value_test { class program { static void main(string[] args) { int maxbatchsize = 3; dictionary<string, datetime> secs = new dictionary<string, datetime>(); secs.add("6571 jt", new datetime(2011, 1, 10)); secs.add("6572 jt", new datetime(2011, 1, 12)); secs.add("6573 jt", new datetime(2011, 1, 12)); secs.add("6574 jt", new datetime(2011, 1, 12)); secs.add("6575 jt", new datetime(2011, 1, 10)); secs.add("6576 jt", new datetime(2011, 1, 11)); secs.add("6577 jt", new datetime(2011, 1, 11)); secs.add("6578 jt", new datetime(2011, 1, 11)); secs.add("6579 jt", new datetime(2011, 1, 11)); var sorted = secs.orderby(o => o.value).groupby(o => o.value); foreach (var date in sorted) { console.write("\nnew batch @ {0} \n", date.key); int batchsize = 0; foreach (var sec in date) { if (batchsize < maxbatchsize) { console.write(" {0} {1} \n", sec.key, sec.value); batchsize++; } else { console.write("\nnew batch @ {0} \n", date.key); console.write(" {0} {1} \n", sec.key, sec.value); batchsize = 1; } } } } } }
you group key, inside result group item index divided desired chunk size.
var chunksize = 3; var sorted = secs .orderby(kv => kv.key) .groupby(o => o.value) .select(g => new {chunks = g.select((o,i) => new {val = o, index = i}) .groupby(item => item.index / chunksize)});
and displaying it:
foreach(var item in sorted.selectmany(item => item.chunks)) { console.writeline("new batch @ " + item.first().val.value); foreach(var element in item) console.writeline(element.val.key); }
Comments
Post a Comment