2012-08-16 57 views
3

如何根據從數據庫中返回的值將枚舉添加到列表中?如果值爲1,則添加到列表中否則不要。根據從數據庫接收到的值將枚舉添加到列表中

這是我或多或少:

Permissions = new List<Permission>() 
{ 
    ((int)data[0]["AllowOverride"] == 1 ? Permission.AllowOverride : "I do not have an else") 
    ((int)data[0]["AllowAttachment"] == 1 ? Permission.AllowAttachment: "I do not have an else") 
}, 

編輯:我建造這個列表作爲對象初始化的一部分。

回答

1

您可以嘗試基於lambda函數,它否定了一個單獨的函數的必要性構建的結果設置該屬性權限。您可以嘗試的東西沿着線:

Permissions = 
    new Func<DataRow, List<Permission>>(permissionData => 
    { 
     List<Permission> permissions = new List<Permission>(); 
     // do all your if checks here to add the necessary permissions to the list 
     return permissions; 
    })(data[0]) 

編輯:我只是改變了一些變量的名稱,以便它實際上沒有使用已經與你的「數據」變量衝突的編譯。

+0

中顯示的方法謝謝,這個答案是正確的! :-) – Landi 2012-08-16 08:44:28

3

無需有條件的經營者在這裏,您只需使用if

Permissions = new List<Permission>(); 

if(((int)data[0]["AllowOverride"]) == 1) 
    Permissions.Add(Permission.AllowOverride); 

if(((int)data[0]["AllowAttachment"]) == 1) 
    Permissions.Add(Permission.AllowAttachment); 
+0

它不會工作,因爲我構建權限列表作爲對象初始值設定項的一部分。 – Landi 2012-08-16 08:23:59

+0

然後不要這樣做。或者將我的代碼抽取到一個方法中並像下面這樣初始化權限列表:'Permissions = Method(data),' – 2012-08-16 08:24:30

+0

我必須這樣做,因爲它是我正在開發的框架的一部分。 permissions屬性是我構建的大對象上大約30個奇特屬性的一部分。 – Landi 2012-08-16 08:26:24

相關問題