Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/297.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C#-在IList中查找不区分大小写的索引_C#_List - Fatal编程技术网

C#-在IList中查找不区分大小写的索引

C#-在IList中查找不区分大小写的索引,c#,list,C#,List,我已经找到了使用不区分大小写的contains来确定IList是否包含元素的答案:IList.contains(元素,StringComparer.CurrentCultureIgnorCase) 但是我想做的是找到IList中与我正在搜索的元素相对应的元素本身。例如,如果IList包含{Foo,Bar},并且我搜索Foo,我希望能够接收Foo 我不担心乘法,IList似乎除了IndexOfwith之外不包含任何函数,这对我帮助不大 编辑:因为我使用的是IList而不是List,所以我没有Ind

我已经找到了使用不区分大小写的contains来确定
IList
是否包含元素的答案:
IList.contains(元素,StringComparer.CurrentCultureIgnorCase)

但是我想做的是找到IList中与我正在搜索的元素相对应的元素本身。例如,如果IList包含
{Foo,Bar}
,并且我搜索
Foo
,我希望能够接收
Foo

我不担心乘法,IList似乎除了
IndexOf
with之外不包含任何函数,这对我帮助不大

编辑:因为我使用的是IList而不是List,所以我没有IndexOf函数,所以这里发布的答案对我帮助不大:)

谢谢,
Arik

要查找项目的索引,可以使用
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));
}
publicstaticintindexof(此列表、字符串值、StringComparer)
{
返回list.FindIndex(i=>comparer.Equals(i,value));
}
public static int caseinsensitiviendexof(此列表,字符串值)
{
返回IndexOf(列表、值、StringComparer.CurrentCultureIgnoreCase);
}
公共静态字符串CaseInsensitiveFind(此列表,字符串值)
{
return list.Find(i=>StringComparer.CurrentCultureIgnoreCase.Equals(i,value));
}

的可能重复项如果您确定没有重复项,则一个
Where()
后跟一个
Single()
给出一行回答:
ilist.Where(l=>l.ToLower()==element.ToLower()).Single()
。否则,如果存在重复的可能性,Mong下面的回答会有所帮助。是关于为什么应该使用
Where()
+
Single()
而不是
Single(谓词)
@MarkoJuvančič我使用的是IList not List,所以我没有IndexOf函数的一些附加信息(可能对您没有帮助)。我找到了那个问题,但没什么帮助。谢谢!这就是我要找的!因为需要尝试捕捉,所以我没有标记为正确。根据这个问题:如果项目不存在并且
Find
返回null,我希望避免必要性
FindIndex
返回-1值。所以我不确定我是否明白为什么你可能需要尝试/捕捉。。。根据这个相关的问题,看起来您也不应该抛出任何异常。