将 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();
}