Programing

IEnumerable

lottogame 2020. 6. 25. 08:06
반응형

IEnumerable 문자열로 [중복]


이 질문에는 이미 답변이 있습니다.

내가 전에이 운 좋게 발견 한 적이 있지만, 지금 가지고 내가 변환 할 수있는 정말 쉬운 방법을 찾을 수 놀라게하고 IEnumerable<char>A를을 string.

내가 생각할 수있는 가장 좋은 방법은 string str = new string(myEnumerable.ToArray());이지만, 나에게 이것이 새로운 것을 만들고 char[]그런 다음 새로운 string것을 만드는 것처럼 보입니다.

나는 이것이 어딘가에 .NET 프레임 워크에 내장 된 일반적인 기능이라고 생각했을 것입니다. 더 간단한 방법이 있습니까?

관심있는 사람들을 위해 이것을 사용하려는 이유는 LINQ를 사용하여 문자열을 필터링하기 때문입니다.

string allowedString = new string(inputString.Where(c => allowedChars.Contains(c)).ToArray());

사용할 수 있습니다 String.Concat().

var allowedString = String.Concat(
    inputString.Where(c => allowedChars.Contains(c))
);

주의 사항 :이 방법은 성능에 영향을 미칩니다. String.Concat특수한 문자 모음은 아니므로 모든 문자가 문자열로 변환 된 것처럼 수행 하고 설명서에서 언급 한 것처럼 연결됩니다 ( 실제로 수행합니다 ). 물론이 작업을 수행하는 기본 방법이 제공되지만 더 잘 수행 할 수 있습니다.

프레임 워크 내에 특별한 경우를 구현해야한다고 생각하지 않으므로 char구현해야합니다. 문자열 빌더에 문자를 추가하는 간단한 루프는 작성하기에 간단합니다.


다음은 개발자 컴퓨터에서 수행 한 몇 가지 벤치 마크입니다.

32 비트 릴리스 빌드에서 300 자 시퀀스에서 1000000 회 반복 :

ToArrayString : 00 : 00 : 03.1695463
연결 : 00 : 00 : 07.2518054
StringBuilderChars : 00 : 00 : 03.1335455
StringBuilder 문자열 : 00 : 00 : 06.4618266
static readonly IEnumerable<char> seq = Enumerable.Repeat('a', 300);

static string ToArrayString(IEnumerable<char> charSequence)
{
    return new String(charSequence.ToArray());
}

static string Concat(IEnumerable<char> charSequence)
{
    return String.Concat(charSequence);
}

static string StringBuilderChars(IEnumerable<char> charSequence)
{
    var sb = new StringBuilder();
    foreach (var c in charSequence)
    {
        sb.Append(c);
    }
    return sb.ToString();
}

static string StringBuilderStrings(IEnumerable<char> charSequence)
{
    var sb = new StringBuilder();
    foreach (var c in charSequence)
    {
        sb.Append(c.ToString());
    }
    return sb.ToString();
}

.Net Core 2.1 릴리스 용으로 편집

.Net Core 2.1 릴리스에 대한 테스트를 반복하면 다음과 같은 결과가 나타납니다.

"Concat"의 1000000 회 반복에는 842ms가 걸렸습니다.

"새 문자열"의 1000000 반복에는 1009ms가 걸렸습니다.

"sb"의 1000000 반복에는 902ms가 걸렸습니다.

요컨대 .Net Core 2.1 이상을 사용하는 경우 Concatking입니다.

자세한 내용은 MS 블로그 게시물 을 참조하십시오.


나는 이것을 다른 질문 의 주제로 만들었지 만 점점 더이 질문에 대한 직접적인 답이되고있다.

내가 변환의 3 개 간단한 방법 중 몇 가지 성능 테스트했던 IEnumerable<char>A를을 string, 그 방법은

새로운 문자열

return new string(charSequence.ToArray());

연결

return string.Concat(charSequence)

StringBuilder

var sb = new StringBuilder();
foreach (var c in charSequence)
{
    sb.Append(c);
}

return sb.ToString();

In my testing, that is detailed in the linked question, for 1000000 iterations of "Some reasonably small test data" I get results like this,

1000000 iterations of "Concat" took 1597ms.

1000000 iterations of "new string" took 869ms.

1000000 iterations of "StringBuilder" took 748ms.

This suggests to me that there is not good reason to use string.Concat for this task. If you want simplicity use the new string approach and if want performance use the StringBuilder.

I would caveat my assertion, in practice all these methods work fine, and this could all be over optimization.


As of .NET 4, many string methods take IEnumerable as arguments.

string.Concat(myEnumerable);

My data is contrary to the results Jodrell posted. First have a look at the extension methods I use:

public static string AsStringConcat(this IEnumerable<char> characters)
{        
    return String.Concat(characters);
}

public static string AsStringNew(this IEnumerable<char> characters)
{
    return new String(characters.ToArray());
}

public static string AsStringSb(this IEnumerable<char> characters)
{
    StringBuilder sb = new StringBuilder();
    foreach (char c in characters)
    {
        sb.Append(c);
    }
    return sb.ToString();
}

My results

With

  • STRLEN = 31
  • ITERATIONS = 1000000

Input

  • ((IEnumerable<char>)RandomString(STRLEN)).Reverse()

Results

  • Concat: 1x
  • New: 3x
  • StringBuilder: 3x

Input

  • ((IEnumerable<char>)RandomString(STRLEN)).Take((int)ITERATIONS/2)

Results

  • Concat: 1x
  • New: 7x
  • StringBuilder: 7x

Input

  • ((IEnumerable<char>)RandomString(STRLEN)) (this is just an upcast)

Results

  • Concat: 0 ms
  • New: 2000 ms
  • StringBuilder: 2000 ms
  • Downcast: 0 ms

I ran this on an Intel i5 760 targeting .NET Framework 3.5.


Another possibility is using

string.Join("", myEnumerable);

I did not measure the performance.


Here is a more succinct version of the StringBuilder answer:

return charSequence.Aggregate(new StringBuilder(), (seed, c) => seed.Append(c)).ToString();

I timed this using the same tests that Jeff Mercado used and this was 1 second slower across 1,000,000 iterations on the same 300 character sequence (32-bit release build) than the more explicit:

static string StringBuilderChars(IEnumerable<char> charSequence)
{
    var sb = new StringBuilder();
    foreach (var c in charSequence)
    {
        sb.Append(c);
    }
    return sb.ToString();
}

So if you're a fan of accumulators then here you go.

참고URL : https://stackoverflow.com/questions/11654190/ienumerablechar-to-string

반응형