如何將可空的guid轉換爲guid?我的意圖是將可空的Guid列表轉換爲guid列表。我怎樣才能做到這一點?如何轉換guid?來引導
13
A
回答
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));
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
1
type?
是Nullable<type>
的簡稱。請參閱the documentation for Nullable。
9
使用此:
List<Guid?> listOfNullableGuids = ...
List<Guid> result = listOfNullableGuids.Select(g => g ?? Guid.Empty).ToList();
這是最簡單的方法。沒有必要爲一些簡單的擴展方法...
相關問題
- 1. LINQ:轉換GUID來串
- 2. 引導程序GUID
- 3. 轉換simple_form標籤來引導
- 4. 如何在轉換爲標識ID時更新guid ID引用
- 5. 轉換GUID爲長
- 6. 如何將字符串轉換爲Guid
- 7. 如何轉換Platform :: String ^至Platform :: Guid^
- 8. 如何將字符串轉換爲Guid?
- 9. 如何將Guid []轉換爲String?
- 10. 如何將guid轉換爲* char
- 11. 如何將byte [100]轉換爲guid
- 12. Firebird .NET Provider GUID轉換
- 13. 將Guid轉換爲Cassandra UUID
- 14. SSIS:將INT轉換爲GUID?
- 15. Flex:將GUID轉換爲Base64
- 16. 將guid轉換爲數值
- 17. 將GUID轉換爲varchar(32)
- 18. .NET本地GUID轉換
- 19. 將GUID轉換爲System.Drawing.Imaging.ImageFormat
- 20. 將URI轉換爲GUID
- 21. 將stringbuilder轉換爲guid
- 22. 將Raw(16)轉換爲GUID
- 23. Twitter引導按鈕轉換
- 24. 引導到WordPress轉換
- 25. Pcap來引用轉換?
- 26. 如何將引導程序導航欄轉換爲wordpress
- 27. 將非託管GUID轉換爲託管指導^
- 28. 如何引用轉換表
- 29. 轉換列表< Guid >到列表< Guid? >
- 30. 引用GUID
多數民衆贊成在有效答覆,但我的意圖是將可空的Guid列表轉換爲guid列表。我怎樣才能做到這一點? – 2011-03-31 10:47:56