转换列表< Guid>列出< GUID? >

时间:2013-04-25 10:45:22

标签: c# linq casting

转换List<的最佳做法是什么? Guid>列出< GUID? >

以下内容无法编译:

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

5 个答案:

答案 0 :(得分:10)

问题似乎改变了几次,所以我会双向展示转换:

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

答案 1 :(得分:7)

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

答案 2 :(得分:3)

像这样的东西

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

答案 3 :(得分:1)

略有不同的方法:

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

答案 4 :(得分:1)

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

}