Best way to convert IEnumerable to string?

后端 未结 6 2045
自闭症患者
自闭症患者 2020-12-10 00:34

Why isn\'t it possible to use fluent language on string?

For example:

var x = \"asdf1234\";
var y = new string(x.TakeWhile(char.IsLetter         


        
6条回答
  •  一整个雨季
    2020-12-10 01:07

    You can very often do better performance-wise. But what does that buy you? Unless this is really the bottle neck for your application and you have measured it to be I would stick to the Linq TakeWhile() version: It is the most readable and maintainable solution, and that is what counts for most of all applications.

    If you really are looking for raw performance you could do the conversion manually - the following was around a factor 4+ (depending on input string length) faster than TakeWhile() in my tests - but I wouldn't use it personally unless it was critical:

    int j = 0;
    for (; j < input.Length; j++)
    {
        if (!char.IsLetter(input[j]))
            break;
    }
    string output = input.Substring(0, j);
    

提交回复
热议问题