List<转换;Guid祝辞List

本文关键字:祝辞 Guid List lt 转换 | 更新日期: 2023-09-27 18:10:55

转换List to List<Guid吗?>

下面的代码不能编译:

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

List<转换;Guid祝辞List<Guid吗?祝辞

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

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