Najkrótszy sposób sprawdzenia null i przypisania innej wartości, jeśli nie

Wyciągam varchar wartości z DB i chcę ustawić string przypisuję je jako"", jeśli są null. Obecnie robię to tak:

if (string.IsNullOrEmpty(planRec.approved_by) == true)
  this.approved_by = "";
else
  this.approved_by = planRec.approved_by.toString();

Wydaje się, że powinien być sposób, aby to zrobić w jednej linii, coś w stylu:

this.approved_by = "" || planRec.approved_by.toString();

Jednak nie mogę znaleźć optymalnego sposobu, aby to zrobić. Czy jest lepszy sposób, czy to, co mam, jest najlepszym sposobem, aby to zrobić?

Author: Alexander Abakumov, 2009-07-13

10 answers

Spróbuj tego:

this.approved_by = IsNullOrEmpty(planRec.approved_by) ? "" : planRec.approved_by.toString();

Możesz również użyć operatora null-coalescing, jak mówili inni-ponieważ nikt nie podał przykładu, który działa z Twoim kodem jest jeden:

this.approved_by = planRec.approved_by ?? planRec.approved_by.toString();

Ale ten przykład działa tylko dlatego, że możliwa wartość dla this.approved_by jest taka sama jak jedna z potencjalnych wartości, na którą chcesz ją ustawić. We wszystkich innych przypadkach będziesz musiał użyć operatora warunkowego, jak pokazałem w moim pierwszym przykładzie.

 73
Author: Andrew Hare,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-07-13 16:37:05

Myślę, że najlepsze, co możesz wymyślić, to

this.approved_by = IsNullOrEmpty(planRec.approved_by) ? string.Empty
                                                      : planRec.approved_by.ToString();

Oczywiście, ponieważ sugerujesz, że approved_by jest object (które nie mogą równać się""), zostanie to przepisane jako

this.approved_by = (planRec.approved_by ?? string.Empty).ToString();
 23
Author: Dmitri Nesteruk,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-07-13 16:33:40
 21
Author: Dave Ward,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-07-13 16:29:53

Szukasz operatora C# coalesce:??. Operator ten przyjmuje argument lewy i prawy. Jeśli lewa strona operatora jest null lub nullable bez wartości, zwróci prawy argument. W przeciwnym razie zwróci lewą.

var x = somePossiblyNullValue ?? valueIfNull;
 18
Author: JaredPar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-07-13 16:31:28

W C#6 istnieje nieco krótszy sposób dla przypadku, w którym planRec.approved_by nie jest ciągiem znaków:

this.approved_by = planRec.approved_by?.ToString() ?? "";
 9
Author: Malcolm,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-07-07 15:06:19

To extend @ Dave ' s answer...jeśli planRec.approved_by jest już ciągiem

this.approved_by = planRec.approved_by ?? "";
 7
Author: Paul Alexander,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:03:08

Użyj operatora C# coalesce:??

// if Value is not null, newValue = Value else if Value is null newValue is YournullValue
var newValue = Value ?? YournullValue;
 7
Author: Ramgy Borja,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-08-23 00:43:22

Można to również zrobić w zapytaniu, na przykład w SQL server, google ISNULL i CASE wbudowanych funkcji.

 1
Author: user133371,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-05-26 18:26:24

Aby przypisać niepustą zmienną bez powtarzania rzeczywistej nazwy zmiennej (i bez przypisywania czegokolwiek, jeśli zmienna jest null!), możesz użyć małej metody pomocniczej z parametrem Action:

public static void CallIfNonEmpty(string value, Action<string> action)
{
    if (!string.IsNullOrEmpty(value))
        action(value);
}

A potem po prostu go użyj:

CallIfNonEmpty(this.approved_by, (s) => planRec.approved_by = s);
 1
Author: Jack Miller,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-11-28 17:36:04

Stosuję metodę rozszerzania SelfChk

static class MyExt {
//Self Check 
 public static void SC(this string you,ref string me)
    {
        me = me ?? you;
    }
}

Następnie użyj jak

string a = null;
"A".SC(ref a);
 -3
Author: Ali Humayun,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-11-05 23:47:36