将List< Guid>转换为List< Guid? >

7

如何将List<Guid>转换为List<Guid?>是最佳实践?

以下代码无法编译:

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

"List< Guid? > to List< Guid? >" 之间有什么区别?我看不出来... - Postback
我认为他的意思是将 List<Guid?> 转换为 List<Guid> - Michael Schnerring
1
不确定如何说“List<Guid> guids = (from... select...);”无法编译会展示你尝试了什么。当然它不会编译。 - Daniel Kelley
1
@voo,GUID 是一个结构体。 - Habib
@DanielKelley:那部分内容与主题无关,已删除。 - Bick
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();

8

类似于这样的东西

return guids.Select(e => new Guid?(e)).ToList();

7
public List<Guid> foo()
{
    return  foo.Where(x=>x != null).Cast<Guid>().ToList();
}

2
返回类型应为 List<Guid> - Michael Schnerring
返回类型应为 List<Guid?>。 - Bick

3
public List<Guid?> foo()
{
    List<Guid> source = getGuidsList();
    return  source.Select(x => new Guid?(x)).ToList();

}

1
稍微不同的方法:

public List<Guid> foo()
{
    return foo.Where(g => g.HasValue).Select(g => g.Value).ToList();
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接