Speaking of Linq single-line handlers)
In general, there is such a task:
There is an IEnumerable<string> containing some strings. And also there is an int[] containing positions for which you need to insert empty lines in the above collection.
Example:
// IEnumerable<string> collection: "Some" "Strings" "To" "Test" "Method" // int[] mask: 1 2 4 // IEnumerable<string> result: "Some" "" "" "Strings" "" "To" "Test" "Method" Linq beauty is to convert the collection without any additional variables or explicit loops. However, I failed to solve the problem without introducing a new variable, so I would like to ask you: which solution will be more elegant?)
My implementations:
Head-on:
int i = 0; List<string> result = new List<string>(); foreach (string x in collection) { while (mask.Contains(i)) { result.Add(string.Empty); ++i; } result.Add(x); ++i; } Same, but through SelectMany :
int i = 0; IEnumerable<string> result = collection.SelectMany(x => { List<string> part = new List<string>(); while (mask.Contains(i)) { part.Add(string.Empty); ++i; } part.Add(x); ++i; return part; }); UPD:
This is usually important in such tasks, so I clarify: mask is an ordered array