A slight variation on Jan's suggestion, without creating a new string:
var lineNumber = input.Take(pos).Count(c => c == '
') + 1;
Using Take
limits the size of the input without having to copy the string data.
You should consider what you want the result to be if the given character is a line feed, by the way... as well as whether you want to handle "foo
bar
baz"
as three lines.
EDIT: To answer the new second part of the question, you could do something like:
var pos = input.Select((value, index) => new { value, index })
.Where(pair => pair.value == '
')
.Select(pair => pair.index + 1)
.Take(line - 1)
.DefaultIfEmpty(1) // Handle line = 1
.Last();
I think that will work... but I'm not sure I wouldn't just write out a non-LINQ approach...
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…