How to convert nullable guid to guid ? My intention is to convert a list of nullable Guid to guid list. how can i do that?

6 Answers

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

the Nullable<T>.value property?

1

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...

new Guid(yourGUID.ToString()) 

Also a possible Solution..

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

being "id" a "Guid?"

Guid.Parse(id.ToString())

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

1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy