Domanda

Qualcosa mi ritrovo a fare sempre di più è il controllo di una stringa per vuota (come in "" o null) e di un operatore condizionale.

Un esempio attuale:

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

Questa è solo un metodo di estensione, è pari a:

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

Dal momento che è vuota e non nullo, ?? volontà non fare il trucco. Una versione string.IsNullOrEmpty() di ?? sarebbe la soluzione perfetta. Sto pensando che ci deve essere un modo più pulito di fare questo (spero!), Ma sono stato in perdita per trovarlo.

Qualcuno sa di un modo migliore per fare questo, anche se è solo in NET 4.0?

È stato utile?

Soluzione

Non c'è un modo integrato per effettuare questa operazione. Si potrebbe rendere il vostro metodo di estensione restituire una stringa o nulla, comunque, che consentirebbe l'operatore coalescenza di lavorare. Questo sarebbe strano, però, e io personalmente preferisco il vostro approccio attuale.

Dal momento che si sta già utilizzando un metodo di estensione, perché non solo fare uno che restituisce il valore o un default:

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

Altri suggerimenti

C # già ci permette di valori sostitutivi per null con ??. Quindi tutti abbiamo bisogno è un'estensione che converte una stringa vuota per null, e poi usare in questo modo:

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

So che questa è una vecchia questione - ma ero alla ricerca di una risposta e nessuna delle precedenti in forma il mio bisogno così come quello che ho finito per usare:

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

Utilizzo:

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

Modifica Un modo ancora più compatto di scrivere questa funzione potrebbe essere:

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

Ho un paio di estensioni di utilità che mi piace usare:

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;
}

Modifica: Ispirato da RSSF 's risposta, sarò l'aggiunta di questa variante alla mia cassetta degli attrezzi da ora in poi:

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

Un metodo di estensione leggermente più veloce rispetto a quanto proposto in precedenza, forse:

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

Uno dei vantaggi del operatore null coalescenza è che cortocircuiti. Quando la prima parte non è nullo, la seconda parte non viene valutata. Questo può essere utile quando il fallback richiede un'operazione costosa.

Ho finito con:

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

Utilizzo:

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

semplicemente uso di un metodo di estensione NullIfEmpty che restituisce sempre null se la stringa è vuota permettendo ?? (Null coalescenza operatore) da utilizzare come normale.

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

In questo modo, allora ?? per essere usato come normale e rende il concatenamento di facile lettura.

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

Come su un metodo di estensione stringa ValueOrDefault ()

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

o restituire null se la stringa è vuota:

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

Non provate queste soluzioni però.

sto usando un metodo di estensione stringa di Coalesce del mio. Dal momento che coloro che sono qui stanno usando LINQ, e absolutelly spreco di risorse per le operazioni intensive di tempo (lo sto usando in cicli stretti), io condividere la mia:

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

Credo che sia abbastanza semplice, e non hanno nemmeno bisogno di perdere tempo con valori di stringa nulla. Utilizzare in questo modo:

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

Io lo uso molto. Una di quelle funzioni "utilità" Non si può vivere senza dopo il primo utilizzo: -)

Mi piace la brevità del seguente estensione metodo QQQ per questo, anche se naturalmente un operatore come? sarebbe meglio. Ma possiamo 1 fino questo permettendo non solo due ma tre valori di opzione stringa da confrontare, che si incontra la necessità di gestire ogni ora e poi (vedi seconda funzione qui sotto).

#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
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top