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)
这是最简单的方法.对于简单的东西,不需要扩展方法......