Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert List< Guid > to List< Guid? >

Tags:

c#

casting

linq

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; 
}
like image 787
Bick Avatar asked Apr 25 '13 10:04

Bick


5 Answers

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();
like image 173
Eren Ersönmez Avatar answered Oct 01 '22 12:10

Eren Ersönmez


public List<Guid> foo()
{
    return  foo.Where(x=>x != null).Cast<Guid>().ToList();
}
like image 39
burning_LEGION Avatar answered Oct 01 '22 10:10

burning_LEGION


Something like this

return guids.Select(e => new Guid?(e)).ToList();
like image 37
Jurica Smircic Avatar answered Oct 01 '22 10:10

Jurica Smircic


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

}
like image 23
Rik Avatar answered Oct 01 '22 11:10

Rik


Slightly different approach:

public List<Guid> foo()
{
    return foo.Where(g => g.HasValue).Select(g => g.Value).ToList();
}
like image 25
PhonicUK Avatar answered Oct 01 '22 12:10

PhonicUK