6

将 List< Guid > 转换为 List< Guid 的最佳做法是什么?>

以下不编译:

public List<Guid?> foo()
{
    List<Guid> guids = getGuidsList();
    return guids; 
}
4

5 回答 5

16

这个问题似乎改变了几次,所以我会以两种方式展示转换:

转换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();
于 2013-04-25T10:56:49.927 回答
7
public List<Guid> foo()
{
    return  foo.Where(x=>x != null).Cast<Guid>().ToList();
}
于 2013-04-25T10:47:13.680 回答
6

像这样的东西

return guids.Select(e => new Guid?(e)).ToList();
于 2013-04-25T10:53:33.617 回答
2
public List<Guid?> foo()
{
    List<Guid> source = getGuidsList();
    return  source.Select(x => new Guid?(x)).ToList();

}
于 2013-04-25T10:56:00.687 回答
1

略有不同的做法:

public List<Guid> foo()
{
    return foo.Where(g => g.HasValue).Select(g => g.Value).ToList();
}
于 2013-04-25T10:50:15.397 回答