I have written this code which takes a one dimensional array, for example:
{"abc","ade","sss","fgw","asd","lka","o"}
and turns it into an array of arrays, combining the elements which do not meet the condition.
For the condition m=>!m.Contains("a")
for example, the output will be:
{{"abc","ade"},{"sss"},{"fgw"},{"asd","lka"},{"o"}}
The code works, but i suspect there is a linq way to do it, and refrain from using temporary variables that i dislike.
public static string[][] combineBy(this string[] inp,Func<string,bool> f)
{
List<string[]> holdElements = new List<string[]>();
while (inp.Length!=0)
{
if (f.Invoke(inp[0]))
{
holdElements.Add(new string[] { inp[0] });
inp = inp.Skip(1).ToArray();
}
else
{
var toAdd = inp.TakeWhile(n => !f.Invoke(n));
holdElements.Add(toAdd.ToArray());
inp = inp.Skip(toAdd.Count()).ToArray();
}
}
return holdElements.ToArray();
}
var toAdd = ...
instead ofholdElements.Add(inp.TakeWhile(n => !f.Invoke(n)));
;-P which is inefficient anyway because you first enumerate theTakeWhile
into an array and then youCount()
instead ofToArray
it in the first place and use theLength
later. \$\endgroup\$ – t3chb0t Jul 26 '16 at 10:33value => !value.contains("a")
. In fact, perhaps,combineBy(list, predicate)
is generallySplitBeforeIf(list, val => !predicate(val))
. \$\endgroup\$ – Heman Gandhi Jul 26 '16 at 15:38