Febin J S
Febin J S

Reputation: 1368

How to convert guid? to guid

How do I convert nullable guid (guid?) to a guid? My intention is to convert a list of nullable Guids to a Guid list.

Upvotes: 22

Views: 61746

Answers (6)

DANIEL SILVA RAMOS
DANIEL SILVA RAMOS

Reputation: 1

being "id" a "Guid?"

Guid.Parse(id.ToString())

Get Guid null and create a guid by turning Guid null into String

Upvotes: -1

N.B.
N.B.

Reputation: 173

new Guid(yourGUID.ToString())

Also a possible Solution..

Upvotes: 6

m0sa
m0sa

Reputation: 10940

Use the ?? operator:

public static class Extension
{
   public static Guid ToGuid(this Guid? source)
   {
       return source ?? Guid.Empty;
   }

   // more general implementation 
   public static T ValueOrDefault<T>(this Nullable<T> source) where T : struct
   {
       return source ?? default(T);
   }
}

You can do this:

Guid? x = null;
var g1 = x.ToGuid(); // same as var g1 = x ?? Guid.Empty;
var g2 = x.ValueOrDefault(); // use more general approach

If you have a a list and want to filter out the nulls you can write:

var list = new Guid?[] {
  Guid.NewGuid(),
  null,
  Guid.NewGuid()
};

var result = list
             .Where(x => x.HasValue) // comment this line if you want the nulls in the result
             .Select(x => x.ValueOrDefault())
             .ToList();

Console.WriteLine(string.Join(", ", result));

Upvotes: 43

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174299

Use this:

List<Guid?> listOfNullableGuids = ...
List<Guid> result = listOfNullableGuids.Select(g => g ?? Guid.Empty).ToList();

This is the simplest way. No need for an extension method for something that simple...

Upvotes: 13

Sjoerd
Sjoerd

Reputation: 75588

type? is short for Nullable<type>. See the documentation for Nullable.

Upvotes: 1

ryuslash
ryuslash

Reputation: 1262

the Nullable<T>.value property?

Upvotes: 15

Related Questions