2017-08-28 45 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