Not sure if the question is titled clearly, but here goes. I have some rather messy code in my ASP.NET MVC 3 app to wrap every 2 (but make this configurable from 1-n) items in a list in a div tag when they are printed out. I’d like to create a LINQ function like so:
// Can't think of a better name
IEnumerable<V> FormattedSubsetList<T, V>(IEnumerable<T> items, int every = 2, [delegate to a method to join the N elements])
{
}
Sorry if this is kind of complicated… I’ll try an example. Let’s say I have a list of Widget. I want to print out the names of all my widgets (let’s say I have 7) and I want every 2 widgets to be inside a div. So if I have…
var list = new List<Widget>();
list.Add(new Widget() { Name = "One" });
//... you get the picture
list.Add(new Widget() { Name = "Seven" });
IEnumerable<string> newList = FormattedSubsetList<Widget, string>(list, 2, (one, two) => (return "<div>" + string.Join(" ", one.Name, two.Name) + "</div>");
string finalString = string.Join(string.Empty, newList);
// finalString == <div>One Two</div><div>Three Four</div><div>Five Six</div><div>Seven</div>
I apologize if anything is unclear but I simply don’t know what sort of thing this is called and have no idea how to go about implementing it. I know my LINQ syntax is a little off in some places too.
Here are two extension methods that will do exactly what you need.
Splitmethod is reusable, it simply splits any IEnumerable into a list of enumerables so each subenumerable has not more thansizeelements. The second methodToFormattedListis the customer method that does what you asked for.How to use:
However, there will be a problem if list has odd number of elements, because args[1] will throw exception on the last element. So you can do: