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>",这是有效的!但,
好吧,因为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)
只需记住添加空值检查,并提供可选的比较器.
您可以将重载中的索引传递给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)