字符串的索引或位置在不可数字符串列表中

now*_*ed. 1 .net c# string .net-4.0 visual-studio-2010

可能重复:
如何获取IEnumerable中元素的索引?

我有以下功能,接受可相关的字符串列表.

我遍历所有字符串,如果它的值等于" TestName"(不区分大小写),我返回它的位置.

    int GetMyTestColumnPosition(IEnumerable<string> TitleNames)
    {
        foreach (var test in TitleNames)
        {
            if (string.Compare(test, "testname", stringComparison.CurrentCultureIgnoreCase) == 0)
            {
                // return TitleNames.IndexOf(test); does not work!
            }
        }
    } 
Run Code Online (Sandbox Code Playgroud)

编辑:我将参数更改为" IList<string>",这是有效的!但,

  1. 如何在可发现的字符串列表中查找字符串的索引或位置?
  2. 为什么nienumerable不支持索引?(我们没有改变列表中的任何值,我们只是找到它的位置!)

zmb*_*mbq 5

好吧,因为IEnumerables用于枚举,所以他们没有IndexOf方法并不奇怪.如果需要,您可以创建扩展方法.

但是,既然你已经在枚举,那么再次计算索引又有什么意义呢?做这样的事情:

int index = 0;
foreach(var test in TitleNames)
{
    if(...) return index;
    index++;
}
Run Code Online (Sandbox Code Playgroud)

想想看,这你想要的扩展方法:

public static int IndexOf(this IEnumerable<T> list, T item)
{
    int index = 0;
    foreach(var l in list)
    {
        if(l.Equals(item))
            return index;
        index++;
    }
    return -1;
 }
Run Code Online (Sandbox Code Playgroud)

只需记住添加空值检查,并提供可选的比较器.


Tim*_*ter 5

您可以将重载中的索引传递给Selector Where

var found = TitleNames
    .Select((str, index) => new { str, index })
    .Where(x => x.str.Equals("testname", StringComparison.CurrentCultureIgnoreCase))
    .FirstOrDefault();

if (found != null)
    return found.index;
return -1;
Run Code Online (Sandbox Code Playgroud)

  • @Tim 如果第一个匹配项是列表中的最后一项,则“Any”将迭代整个列表以查找该匹配项,然后“First”将再次迭代以查找第一项。 (2认同)
  • @Rawling:太棒了!;)(已编辑) (2认同)