2011-03-31 43 views

回答

20

使用??操作:

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); 
    } 
} 

你可以這樣做:

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

如果你有AA列表和wan't過濾掉空,你可以寫:

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)); 
+1

多數民衆贊成在有效答覆,但我的意圖是將可空的Guid列表轉換爲guid列表。我怎樣才能做到這一點? – 2011-03-31 10:47:56

5

the Nullable<T>.value property?

+0

非常感謝ryuslash,你的回答真的幫了我。 – Mitch 2012-04-11 20:57:02

+0

我同意;不需要擴展類型;如果你知道可空類型包含一個真正的Guid,只需使用.Value屬性即可。 – HBlackorby 2015-08-24 20:26:01

9

使用此:

List<Guid?> listOfNullableGuids = ... 
List<Guid> result = listOfNullableGuids.Select(g => g ?? Guid.Empty).ToList(); 

這是最簡單的方法。沒有必要爲一些簡單的擴展方法...