开发者

How to convert guid? to guid

How to convert nullable guid to guid ? My intention is to convert a list of nullable Guid to guid list. how can i do tha开发者_如何学编程t?


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜