c# - Splitting a list of objects into multiple separate lists based on a given criteria -
consider following list:
var headers = new list<tableheader>() { new tableheader("column1", 3), new tableheader("column2", 2), new tableheader("column3", 1, alignment.right), new tableheader("column4", 1), new tableheader("column5", 1), new tableheader("column6", 6, alignment.right), new tableheader("column7", 2, alignment.right), };
where second parameter in tableheader constructor width.
i'd split above list n separate lists each of containing total maximum number of w width. example, if w equals 7, need 3 lists containing tableheader objects, follows:
- column1, column2, column3, column4 (since 3+2+1+1 <= 7).
- column5, column6
- column7
any highly appreciated.
this i've implemented. better idea?
public static ienumerable<ienumerable<t>> split<t>(this ienumerable<t> source, double maxwidth) t : tableheader { while (source.any()) { int skip = 0; double totalwidth = 0; yield return source.takewhile(h => { totalwidth += h.width; if (totalwidth <= maxwidth) skip++; return totalwidth <= maxwidth; }); source = source.skip(skip); } }
Comments
Post a Comment