2017-08-28 18 views
0

我已經找到答案,確定一個IList<string>包含一個元素使用不區分大小寫包含:ilist.Contains(element, StringComparer.CurrentCultureIgnoreCase)C# - 查找不區分大小寫指數的IList

但是我希望做的就是找到內對應的元素本身IList是我正在尋找的元素。例如,如果IList包含{Foo, Bar}並且我搜索fOo我希望能夠收到Foo

我並不擔心倍數,並且IList似乎沒有包含IndexOf以外的任何功能,但對我沒有多大幫助。

編輯:由於我使用的IList,而不是名單,我不具備的功能的IndexOf,所以貼在這裏的答案並不能幫助我很多:)

感謝, 阿里克

+0

的可能的複製[如何忽略在列表中的情況下,靈敏度(https://stackoverflow.com/questions/3107765/how-to-ignore-the-case-sensitivity-in-liststring) –

+2

如果你確定沒有重複,那麼在Where()後面加上Single()會給你一個單行的答案:'ilist.Where(l => l.ToLower()== element.ToLower ))。單()'。否則,如果有可能發生重複,Mong的答案會有所幫助。 [這裏](https://stackoverflow.com/questions/21194750/which-is-faster-singlepredicate-or-wherepredicate-single)是一些額外的(可能對你沒有用)信息爲什麼你應該使用'Where() '+'Single()'對'Single(謂詞)'。 –

+0

@MarkoJuvančič我使用IList而不是List,所以我沒有IndexOf函數。我發現這個問題,但沒有多大幫助。 –

回答

1

要查找物品的索引,可以使用FindIndex函數與自定義謂詞進行不區分大小寫匹配。同樣,您可以使用Find獲取實際項目。

我可能會創建一個擴展方法用作重載。

public static int IndexOf(this List<string> list, string value, StringComparer comparer) 
{ 
    return list.FindIndex(i => comparer.Equals(i, value)); 
} 

public static int CaseInsensitiveIndexOf(this List<string> list, string value) 
{ 
    return IndexOf(list, value, StringComparer.CurrentCultureIgnoreCase); 
} 

public static string CaseInsensitiveFind(this List<string> list, string value) 
{ 
    return list.Find(i => StringComparer.CurrentCultureIgnoreCase.Equals(i, value)); 
} 
+0

謝謝!這就是我一直在尋找的! –

+0

因爲需要嘗試捕獲,所以我沒有標記爲正確。根據這個問題:https://stackoverflow.com/questions/8687113/if-condition-vs-exception-handler我想避免的必要性 –

+1

FindIndex返回-1值,如果該項目不存在和'Find'返回null。所以我不確定我會得到爲什麼你可能需要嘗試/捕獲...正如每個鏈接的問題,事實上,你似乎不應該拋出任何異常。 – Reddog