Another LINQ-based solution. (Perhaps not the most efficient, but it allows you to get compressed code and works to group into arbitrary group sizes).
1) Define a new query statement, InGroupsOf :
public static IEnumerable<T[]> InGroupsOf<T>(this IEnumerable<T> parts, int groupSize) { IEnumerable<T> partsLeft = parts; while (partsLeft.Count() >= groupSize) { yield return partsLeft.Take(groupSize).ToArray<T>(); partsLeft = partsLeft.Skip(groupSize); } }
2) Secondly, apply it to your input:
// define your input string: string input = "test1, 1, anotherstring, 5, yetanother, 400"; // split it, remove excessive whitespace from all parts, and group them together: IEnumerable<string[]> pairedInput = input .Split(',') .Select(part => part.Trim()) .InGroupsOf(2); // <-- used here! // see if it worked: foreach (string[] pair in pairedInput) { Console.WriteLine(string.Join(", ", pair)); }
stakx
source share