2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

null安全とLINQ

Last updated at Posted at 2020-03-25

##前書
流石にLINQまでフロー解析はしてくれないらしい

##直面した場面


public static int? ToIntOrNull(int num)
{
    return num % 2 == 0 ? (int?)null : num;
}

//
public static IEnumerable<int> TestFunc1()
{
    //kは非nullが確定しているが警告が出る
    //CS8629	Null 許容値型は Null になる場合があります。
    return Enumerable.Range(0, 10)
        .Select((i) => ToIntOrNull(i))
        .Where((j) => j != null)
        .Select((k) => (int)k);
}
public static IEnumerable<int> TestFunc2()
{
    //!演算子をつければ警告は出ない
    return Enumerable.Range(0, 10)
        .Select((i) => ToIntOrNull(i))
        .Where((j) => j != null)
        .Select((k) => (int)k!);
}

##追記
コメントを頂いたのでそのまま転記
OfType()を使えばすっきり綺麗に書けるそうです

public static IEnumerable<int> TestFunc3()
{
    return Enumerable.Range(0, 10)
        .Select((i) => ToIntOrNull(i))
        .OfType<int>();
// 1,3,5,7,9
}
2
1
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?