Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use Linq to create an IEnumerable based on line breaks in a string?

Tags:

c#

linq

I have some C# code in a string that looks like this:

content = 'var expData = 
                        details.Select(x => x.Explanation.TextWithHtml).ToList();
var score = resData.SequenceEqual(ansData);
var explanation = "";';

How can I make it so the code is converted to the following using LINQ?

<td>01</td><td>var expData = 
                  details.Select(x => x.Explanation.TextWithHtml ).ToList();</td>
<td>02</td><td>var score = resData.SequenceEqual(ansData);</td>
<td>03</td><td>var explanation = "";</td>
like image 924
Alan2 Avatar asked Dec 15 '22 18:12

Alan2


2 Answers

It sounds like you want something like:

var lines = text.Split(new[] { "\r\n" }, StringSplitOptions.None)
                .Select((line, index) => 
                    string.Format("<td>{0:00}</td><td>{1}</td>",
                       index + 1, EscapeHtml(line)));

You'd need to write EscapeHtml though - you don't want tags in your C# code to still end up as tags in the HTML!

like image 125
Jon Skeet Avatar answered Jan 29 '23 22:01

Jon Skeet


This should work, you can get the index from Enumerable.Select:

IEnumerable<String> code =
    content.Split(new[] { Environment.NewLine }, StringSplitOptions.None)
           .Select((line, index) => 
                string.Format("<td>{0}</td><td>{1}</td>", 
                    (index + 1).ToString("D2"), line));

How to: Pad a Number with Leading Zeros

like image 27
Tim Schmelter Avatar answered Jan 29 '23 22:01

Tim Schmelter