簡體   English   中英

比if / else檢查索引數組更好的方法

[英]A better way than if/else to check index array

我得到索引超出范圍錯誤,我明白為什么得到它。 我正在尋找的也許是我可能不知道的c#的某些功能,而不是使用笨拙的if / else語句。

如果Active Directory用戶沒有職稱,則會出錯,因為它不會加載該屬性,因此據我所知,甚至不存在rs.Propterties [“ title”]。

有沒有比if(rs.Properties [“ title”]。Count)更干凈的方法

user.jobTitle = rs.Properties["title"][0].ToString();

我一直在尋找像??這樣的不同運算符。 和?:但無法弄清楚如何使其正常工作。

rs.Properties的類型為SearchResult,來自:

使用System.DirectoryServices;
使用System.DirectoryServices.ActiveDirectory;
使用System.DirectoryServices.AccountManagement;

怎么樣:

user.jobTitle = (rs.Properties["title"].FirstOrDefault() ?? "").ToString();

假設rs.Properties["title"]的類型為IEnumerable<object>或類似類型。 如果只是IEnumerable ,則需要類似以下內容:

user.jobTitle = (rs.Properties["title"]
                   .Cast<object>()
                   .FirstOrDefault() ?? "").ToString();

如果集合為空,則FirstOrDefault調用將返回null。

(現在我們知道rs的類型,看起來后者是必需的。)

當然,您可能希望將其包裝到自己的擴展方法中:

public static string GetFirstProperty(this SearchResult result,
                                      string propertyName,
                                      string defaultValue)
{
    return result.Properties[propertyName]
                 .Cast<object>()
                 .FirstOrDefault() ?? defaultValue).ToString();
}

選項1

user.jobTitle = rs.Properties.Contains("Title") ? rs.Properties["Title"][0].ToString() : string.Empty;

選項2

public static class SearchResultHelper
{
    public static string GetValue(this SearchResult searchResult, string propertyName)
    {
        return searchResult.Properties.Contains(propertyName) ? searchResult.Properties[propertyName][0].ToString() : string.Empty;
    }
}

通話看起來像

user.JobTitle = rs.Properties.GetValue("Title")

感謝http://www.codeproject.com/KB/system/getuserfrmactdircsharp.aspx作為廣告示例

這是您要找的東西嗎?

user.jobTitle = rs.Properties["title"]
    .Cast<object>()
    .FirstOrDefault()
    .MaybePipe(x => x.ToString());

我到處都使用的輔助函數:

public static TResult MaybePipe(this T obj, Func<T, TResult> func)
{
    return obj != null ? func(obj) : default(T);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM