linq能否以某种方式用于查找数组中的值的索引?
例如,此循环定位数组中的键索引。
for (int i = 0; i < words.Length; i++)
{
if (words[i].IsKey)
{
keyIndex = i;
}
}
发布于 2009-11-20 22:12:50
int keyIndex = Array.FindIndex(words, w => w.IsKey);
这实际上会得到整数索引,而不是对象,而不管您创建了什么自定义类
发布于 2012-10-19 00:09:00
int keyIndex = words.TakeWhile(w => !w.IsKey).Count();
发布于 2009-11-20 01:21:35
如果你想找到你可以使用的词
var word = words.Where(item => item.IsKey).First();
这将为您提供IsKey为true的第一个项目(如果可能没有,则可能需要使用.FirstOrDefault()
要同时获取项和索引,您可以使用
KeyValuePair<WordType, int> word = words.Select((item, index) => new KeyValuePair<WordType, int>(item, index)).Where(item => item.Key.IsKey).First();
https://stackoverflow.com/questions/1764970
复制相似问题