What is the best practice to convert List< Guid > to List< Guid? >
The following does not compile:
public List<Guid?> foo()
{
List<Guid> guids = getGuidsList();
return guids;
}
The question seemed to change a couple times, so I'll show the conversion both ways:
Convert List<Guid?>
to 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
Convert List<Guid>
to List<Guid?>
:
var nullableGuids = guids.Cast<Guid?>().ToList();
public List<Guid> foo()
{
return foo.Where(x=>x != null).Cast<Guid>().ToList();
}
Something like this
return guids.Select(e => new Guid?(e)).ToList();
public List<Guid?> foo()
{
List<Guid> source = getGuidsList();
return source.Select(x => new Guid?(x)).ToList();
}
Slightly different approach:
public List<Guid> foo()
{
return foo.Where(g => g.HasValue).Select(g => g.Value).ToList();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With