How to convert guid? to guid
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));
the Nullable<T>.value
property?
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...