Best way to convert IEnumerable to string?

后端 未结 6 2075
自闭症患者
自闭症患者 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 00:51

    Assuming that you're looking predominantly for performance, then something like this should be substantially faster than any of your examples:

    string x = "asdf1234";
    string y = x.LeadingLettersOnly();
    
    // ...
    
    public static class StringExtensions
    {
        public static string LeadingLettersOnly(this string source)
        {
            if (source == null)
                throw new ArgumentNullException("source");
    
            if (source.Length == 0)
                return source;
    
            char[] buffer = new char[source.Length];
            int bufferIndex = 0;
    
            for (int sourceIndex = 0; sourceIndex < source.Length; sourceIndex++)
            {
                char c = source[sourceIndex];
    
                if (!char.IsLetter(c))
                    break;
    
                buffer[bufferIndex++] = c;
            }
            return new string(buffer, 0, bufferIndex);
        }
    }
    

提交回复
热议问题