List< Guid > を List< Guid に変換するベスト プラクティスは何ですか? >
以下はコンパイルされません。
public List<Guid?> foo()
{
List<Guid> guids = getGuidsList();
return guids;
}
質問は数回変更されたように見えたので、両方の方法で変換を示します。
List<Guid?>
に変換List<Guid>
:
var guids = nullableGuids.OfType<Guid>().ToList();
// note that OfType() implicitly filters out the null values,
// a Cast() would throw a NullReferenceException if there are any null values
List<Guid>
に変換List<Guid?>
:
var nullableGuids = guids.Cast<Guid?>().ToList();
public List<Guid> foo()
{
return foo.Where(x=>x != null).Cast<Guid>().ToList();
}
このようなもの
return guids.Select(e => new Guid?(e)).ToList();
public List<Guid?> foo()
{
List<Guid> source = getGuidsList();
return source.Select(x => new Guid?(x)).ToList();
}
少し異なるアプローチ:
public List<Guid> foo()
{
return foo.Where(g => g.HasValue).Select(g => g.Value).ToList();
}