I need some advice on how I can change the implementation of some code. I have input files that hold data that’s read into a class:
This is line 1
This is line 2
This is line 3
I have code that writes out this data to HTML
@foreach (var item in Model.NoteDetails)
{
<li>@item</li>
}
Now I am being asked to accept a different kind of input file:
This is line 1
Data Line - two
Data Line - two two
Another line
What I need to do is to have my code check for lines that start with the same text just when followed by a hyphen. Then the code should group by this. So the output resulting from this would need to be:
This is line 1
Data Line
- two
- two two
Another line
I am not sure if this is possible with LINQ. Maybe it is better if I use an array or something. The problem is I need to be able to look ahead and then when I find that a line’s not in a group then I print out the lines and do or do not start another group. I think it’s more than is possible with LINQ. I know there are a lot of LINQ experts out there and would appreciate any advice.
Using the ChunkBy extension method on MSDN (any my own simple ToEnumerable extension method) you can do this with LINQ. End product looks nice, but there’s a lot of extension method magic helping things along:
EDIT
I added another extension method (Interleave). This is used to interleave new lines where necessary. Output now fully matches your requirements.
How it works:
First we need keys. If there’s a dash, use what’s before the first dash, otherwise use string.Empty.
This gives us:
Then when we ChunkBy we’ve got 3 groups, (line 1), (line 2,line 3) and (line 4). Each group also has a Key.
We can now use this info to reassemble the data in the required format.