Here are two extension methods that will do exactly what you need. Split method is reusable, it simply splits any IEnumerable into a list of enumerable objects, so each subenumerable has at most size elements. The second ToFormattedList method is a client method that does what you requested.
public static class Extenstions { public static IEnumerable<TRestul> ToFormattedList<TElement, TRestul>( this IEnumerable<TElement> source, int count, Func<List<TElement>, TRestul> formatter) { return source.Split(count).Select(arg => formatter(arg.ToList())); } public static IEnumerable<IEnumerable<T>> Split<T>(this IEnumerable<T> source, int size) { var i = 0; return from element in source group element by i++ / size into splitGroups select splitGroups.AsEnumerable(); } }
How to use:
var list = new List<Widget> { new Widget { Name = "One" }, new Widget { Name = "Two" }, new Widget { Name = "Three" }, new Widget { Name = "Four" }, new Widget { Name = "Five" }, new Widget { Name = "Six" }, new Widget { Name = "Seven" }, new Widget { Name = "Eight" } }; var newList = list.ToFormattedList(2, args => "<div>" + args[0].Name + args[1].Name + "</div>"); var finalString = string.Join(string.Empty, newList);
However, a problem will arise if there is an odd number of elements in the list, because args [1] will throw an exception for the last element. So you can do:
var newList = list.ToFormattedList(2, args => "<div>" + string.Join(" ", args.Select(arg => arg.Name)) + "/<div>");
source share