C
C#8mo ago
Moods

Convert to LINQ

How would y'all make this using just LINQ functions?
IEnumerable<string[]> SequenceOfGrids(string[] input)
{
var res = new List<string[]>();

int start = 0;

for(int a = 1; a < input.Length; a++)
{
if(string.IsNullOrWhiteSpace(input[a]))
{
res.Add(input[start..a]);
start = a + 1;
}
}

res.Add(input[start..^0]);

return res;
}
IEnumerable<string[]> SequenceOfGrids(string[] input)
{
var res = new List<string[]>();

int start = 0;

for(int a = 1; a < input.Length; a++)
{
if(string.IsNullOrWhiteSpace(input[a]))
{
res.Add(input[start..a]);
start = a + 1;
}
}

res.Add(input[start..^0]);

return res;
}
basically input is a collection of grids separated by one whitespace line, and i want to transform it into a list of the grids here is a cutout of an example of such a grid
123
456
789

123
456
789
123
456
789

123
456
789
8 Replies
Omnissiah
Omnissiah8mo ago
shouldnt this if(string.IsNullOrWhiteSpace(input[a])) be == false?
Pobiega
Pobiega8mo ago
nah its looking for the next blank line, then "chopping" there I would probably just yield results myself, otherwise this is mostly fine dont think you can easily rewrite this to "only LINQ". Probably can with the help of SuperLinq or MoreLinq thou
Omnissiah
Omnissiah8mo ago
but input is a string[]. not a string am i dumb, something is odd no ok maybe i got there
Pobiega
Pobiega8mo ago
input[a] is a string if that string is fully blank, or I guess pure whitespace, it counts as a delimiter this type of input is very common in Advent of Code, but the usual approach there is to just split the entire string on \n\n first
Omnissiah
Omnissiah8mo ago
and then it goes for the next group can't you use the other linq operation for this, how is it called i was thinking Chunk, but it's not it, you could probably do a GroupBy(not empty/space) maybe
Moods
MoodsOP8mo ago
Yeahhhh I could have yielded it tbh but besides that I couldn’t think of anything else I will look into chunk thanks :)
Pobiega
Pobiega8mo ago
neither chunk or groupby will work here thou
Omnissiah
Omnissiah8mo ago
just for fun, a way could be being fp about it
var grpd = input
.Select((s, id) => (s, id))
.Where(x => string.IsNullOrWhiteSpace(x.s) || x.id == (input.Length - 1))
.Aggregate((ret: Array.Empty<string[]>(), prevId: 0), (acc, item) => ([.. acc.ret, strs[acc.prevId..(item.id + 1)]], item.id + 1))
.ret;
var grpd = input
.Select((s, id) => (s, id))
.Where(x => string.IsNullOrWhiteSpace(x.s) || x.id == (input.Length - 1))
.Aggregate((ret: Array.Empty<string[]>(), prevId: 0), (acc, item) => ([.. acc.ret, strs[acc.prevId..(item.id + 1)]], item.id + 1))
.ret;
but there are could be other edge cases to work out and c# is probably not the language for this
Want results from more Discord servers?
Add your server