如何将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();
类似于这样的东西
return guids.Select(e => new Guid?(e)).ToList();
public List<Guid> foo()
{
return foo.Where(x=>x != null).Cast<Guid>().ToList();
}
List<Guid>
。 - Michael Schnerringpublic 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();
}
List<Guid?>
转换为List<Guid>
。 - Michael Schnerring