Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert guid? to guid

Tags:

c#-4.0

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?

like image 517
Febin J S Avatar asked Mar 31 '11 10:03

Febin J S


People also ask

How do I convert Guid?

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.

Can you convert a Guid to an int?

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.

What is a Guid C#?

C# Guid. A GUID (Global Unique IDentifier) is a 128-bit integer used as a unique identifier.


1 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));
like image 184
m0sa Avatar answered Oct 08 '22 08:10

m0sa