IT story

??

hot-time 2020. 6. 9. 07:59
반응형

?? 빈 문자열에 대한 병합?


내가 점점 더 많이하고있는 것은 문자열이 비어 있거나 (있는 ""또는 null 인) 조건부 연산자를 확인하는 것입니다.

현재 예 :

s.SiteNumber.IsNullOrEmpty() ? "No Number" : s.SiteNumber;

이것은 확장 방법 일 뿐이며 다음과 같습니다.

string.IsNullOrEmpty(s.SiteNumber) ? "No Number" : s.SiteNumber;

비어 있고 null ??이 아니기 때문에 트릭을 수행하지 않습니다. string.IsNullOrEmpty()버전은 ??완벽한 솔루션이 될 것입니다. 나는 이것을하는 더 깨끗한 방법이 있어야한다고 생각하지만 (나는 희망한다!), 나는 그것을 찾지 못했습니다.

.Net 4.0에만있는 사람 이라도이 작업을 수행하는 더 좋은 방법을 알고 있습니까?


이를위한 기본 제공 방법은 없습니다. 그러나 확장 메소드가 문자열 또는 널을 리턴하도록하여 병합 연산자가 작동 할 수 있습니다. 그러나 이것은 이상 할 것입니다. 개인적으로 귀하의 현재 접근 방식을 선호합니다.

이미 확장 메서드를 사용하고 있으므로 값이나 기본값을 반환하는 확장 메서드를 만드는 것이 어떻습니까?

string result = s.SiteNumber.ConvertNullOrEmptyTo("No Number");

C #은 이미 우리가 값을 대체 할 수 있습니다 null??. 따라서 빈 문자열을로 변환하는 확장명 만 있으면 null다음과 같이 사용합니다.

s.SiteNumber.NullIfEmpty() ?? "No Number";

나는 이것이 오래된 질문이라는 것을 알고 있지만 대답을 찾고 있었고 위의 어느 것도 내 필요와 내가 사용한 것을 충족시키지 못했습니다.

private static string Coalesce(params string[] strings)
{
    return strings.FirstOrDefault(s => !string.IsNullOrEmpty(s));
}

용법:

string result = Coalesce(s.SiteNumber, s.AltSiteNumber, "No Number");

편집 : 이 함수를 작성하는 훨씬 간단한 방법은 다음과 같습니다.

static string Coalesce(params string[] strings) => strings.FirstOrDefault(s => !string.IsNullOrEmpty(s));

사용하고 싶은 몇 가지 유틸리티 확장이 있습니다.

public static string OrDefault(this string str, string @default = default(string))
{
    return string.IsNullOrEmpty(str) ? @default : str;
}

public static object OrDefault(this string str, object @default)
{
    return string.IsNullOrEmpty(str) ? @default : str;
}

편집 : sfsr 의 답변에서 영감을 얻어 지금부터 도구 상자 에이 변형을 추가 할 것입니다.

public static string Coalesce(this string str, params string[] strings)
{
    return (new[] {str})
        .Concat(strings)
        .FirstOrDefault(s => !string.IsNullOrEmpty(s));
}

이전에 제안 된 것보다 약간 빠른 확장 방법 :

public static string Fallback(this string @this, string @default = "")
{
    return (@this == null || @this.Trim().Length == 0) ? @default : @this;
}

널 병합 연산자의 장점 중 하나는 단락되는 것입니다. 첫 번째 부분이 null이 아닌 경우 두 번째 부분은 평가되지 않습니다. 폴백에 값 비싼 작업이 필요한 경우에 유용 할 수 있습니다.

나는 결국 :

public static string Coalesce(this string s, Func<string> func)
{
    return String.IsNullOrEmpty(s) ? func() : s;
}

용법:

string navigationTitle = model?.NavigationTitle.
    Coalesce(() => RemoteTitleLookup(model?.ID)). // Expensive!
    Coalesce(() => model?.DisplayName);

문자열이 비어 있으면 항상 null을 반환하는 NullIfEmpty 확장 메서드를 사용하면됩니다. (Null Coalescing Operator)가 정상적으로 사용됩니다.

public static string NullIfEmpty(this string s)
{
    return s.IsNullOrEmpty() ? null : s;
}

그러면 허용됩니다 ?? 정상적으로 사용되며 체인을 쉽게 읽을 수 있습니다.

string string1 = string2.NullIfEmpty() ?? string3.NullIfEmpty() ?? string4;

문자열 확장 메서드 ValueOrDefault ()는 어떻습니까

public static string ValueOrDefault(this string s, string sDefault)
{
    if (string.IsNullOrEmpty(s))
        return sDefault;
    return s;
}

문자열이 비어 있으면 null을 반환합니다.

public static string Value(this string s)
{
    if (string.IsNullOrEmpty(s))
        return null;
    return s;
}

그래도 이러한 솔루션을 시도하지 않았습니다.


내 자신의 문자열 Coalesce 확장 방법을 사용하고 있습니다. 여기에있는 사람들은 LINQ를 사용하고 시간 집약적 인 작업을 위해 리소스를 낭비하고 있기 때문에 (나는 그것을 꽉 찬 루프에서 사용하고 있습니다) 공유 할 것입니다.

public static class StringCoalesceExtension
{
    public static string Coalesce(this string s1, string s2)
    {
        return string.IsNullOrWhiteSpace(s1) ? s2 : s1;
    }
}

I think it is quite simple, and you don't even need to bother with null string values. Use it like this:

string s1 = null;
string s2 = "";
string s3 = "loudenvier";
string s = s1.Coalesce(s2.Coalesce(s3));
Assert.AreEqual("loudenvier", s);

I use it a lot. One of those "utility" functions you can't live without after first using it :-)


I like the brevity of the following extension method QQQ for this, though of course an operator like? would be better. But we can 1 up this by allowing not just two but three string option values to be compared, which one encounters the need to handle every now and then (see second function below).

#region QQ

[DebuggerStepThrough]
public static string QQQ(this string str, string value2)
{
    return (str != null && str.Length > 0)
        ? str
        : value2;
}

[DebuggerStepThrough]
public static string QQQ(this string str, string value2, string value3)
{
    return (str != null && str.Length > 0)
        ? str
        : (value2 != null && value2.Length > 0)
            ? value2
            : value3;
}


// Following is only two QQ, just checks null, but allows more than 1 string unlike ?? can do:

[DebuggerStepThrough]
public static string QQ(this string str, string value2, string value3)
{
    return (str != null)
        ? str
        : (value2 != null)
            ? value2
            : value3;
}

#endregion

참고URL : https://stackoverflow.com/questions/2420125/coalesce-for-empty-string

반응형