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?
The Parse method trims any leading or trailing white space from input and converts the string representation of a GUID to a Guid value. This method can convert strings in any of the five formats produced by the ToString(String) and ToString(String, IFormatProvider) methods, as shown in the following table.
An integer uses 32 bits, whereas a GUID is 128 bits - therefore, there's no way to convert a GUID into an integer without losing information, so you can't convert it back.
C# Guid. A GUID (Global Unique IDentifier) is a 128-bit integer used as a unique identifier.
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));
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