如何转换guid?指导

Feb*_*J S 14 c#-4.0

如何将可空的guid转换为guid?我的目的是将可以为空的Guid列表转换为guid列表.我怎样才能做到这一点?

m0s*_*0sa 27

使用??运营商:

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);
   }
}
Run Code Online (Sandbox Code Playgroud)

你可以这样做:

Guid? x = null;
var g1 = x.ToGuid(); // same as var g1 = x ?? Guid.Empty;
var g2 = x.ValueOrDefault(); // use more general approach
Run Code Online (Sandbox Code Playgroud)

如果你有一个列表并希望过滤掉你可以写的空值:

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));
Run Code Online (Sandbox Code Playgroud)


Dan*_*rth 10

用这个:

List<Guid?> listOfNullableGuids = ...
List<Guid> result = listOfNullableGuids.Select(g => g ?? Guid.Empty).ToList();
Run Code Online (Sandbox Code Playgroud)

这是最简单的方法.对于简单的东西,不需要扩展方法......


ryu*_*ash 9

Nullable<T>.value财产?


小智 5

new Guid(yourGUID.ToString())
Run Code Online (Sandbox Code Playgroud)

也是一个可能的解决方案..