我想要得到一个数组的索引,我已经用Array.IndexOf(array, value)
完成了。这适用于一个值,但我希望每次出现该值并将索引存储到另一个数组中。例如,名称'tom'在数组中出现5次,我想要查找每个索引位置。得到一个数组的索引多次,然后将它们存储在一个数组中c#
1
A
回答
3
1
您可以使用LINQ的Select
过载,它使用元素的索引,以及像:
var indices = stringArray.Select((s, i) => new {Value = s, Index = i})
.Where(r => r.Value == "tom")
.Select(r => r.Index);
2
如果我没有记错的话,你可以在其他参数添加到IndexOf()
,这将让您指定在数组中开始。这应该给你或多或少你所需要的:
var indices = new List<int>();
int i = Array.IndexOf(array, val);
while(i > -1){
indices.Add(i);
i = Array.IndexOf(array, val, i+1);
}
// ... and if it is important to have the result as an array:
int[] result = indices.ToArray();
实例:
var array = new int[]{ 1, 2, 3, 3, 4, 5, 3, 6, 7, 8, 3};
int val = 3;
var indices = new List<int>();
int i = Array.IndexOf(array, val);
while(i > -1){
indices.Add(i);
i = Array.IndexOf(array, val, i+1);
}
// ... and if it is important to have the result as an array:
int[] result = indices.ToArray();
编辑:刚刚意识到一个while循环可能比for循环更清洁了很多这个。
编辑2:由于大众需求(见下文评论),here`s原来的靓丽无基本的循环,只是重新引入您的阅读快感:
for(int i = Array.IndexOf(array, val); i > -1; i = Array.IndexOf(array, val, i+1)){
indices.Add(i);
}
2
可以创建一个扩展方法来做到这一点
namespace Extensions
{
public static class ArrayExtension
{
public static IEnumerable<int> GetIndicesOf<T>(this T[] target, T val, int start = 0)
{
EqualityComparer<T> comparer = EqualityComparer<T>.Default;
for (int i = start; i < target.Length; i++)
{
if (comparer.Equals(target[i], val))
{
yield return i;
}
}
}
}
}
添加using语句命名空间w^ith扩展方法using Extensions;
在您要调用它的文件中。
然后调用它只需执行以下操作即可获取索引。
IEnumerable<int> indices = array.GetIndicesOf(value);
,或者得到一个数组只是做
int[] indicies = array.GetIndicesOf(value).ToArray();
3
该解决方案是像以前的一个,但运行速度更快:
string value = "tom";
int[] indices = stringArray.Where(s => s != null)
.Select((s, i) => s.Equals(value) ? i: -1)
.Where(i => i >= 0)
.ToArray();
相关问题
- 1. 生成50个随机数并将它们存储到一个数组中C++
- 2. 在一个类中存储char数组然后返回它
- 3. C - 在一个2d char *数组中存储多个char数组
- 4. 获取按钮并将它们存储在一个数组中
- 5. 得到一个数组的索引
- 6. 将数组中的第一个元素存储在另一个数组中,如果它们存在
- 7. 将char数组存储到另一个数组中 - c
- 8. C通过指针将多个int数组存储到另一个数组中
- 9. 在一个数组中的多个数组中存储多个数组Python/Numpy
- 10. 将多个函数的数据存储在一个数组中
- 11. PHP从多维数组中找到值,然后将它们放在一个数组中
- 12. 将数组存储在另一个数组中C
- 13. 将几个单词存储在会话数组中,然后显示它们
- 14. 在一个数组中输入Floats然后将它们加在一起
- 15. 如何在Zend Lucene中将一个数组数组存储到一个索引文档中?
- 16. 在rdlc split(winform)得到数组的最后一个索引值
- 17. 如何在另一个数组中搜索一个数组,然后将结果放入第三个数组中?
- 18. 使用它们的索引号一次对多个数组进行排序?
- 19. 一维数组中的多个索引
- 20. 将多个值保存在一个会话变量中,然后检索它们
- 21. 索引一个索引数组的多维numpy数组
- 22. 引用到对价值的一个数组列表,然后比较它们
- 23. 我想从用户那里得到所需的整数数量并将它们存储到一个数组中
- 24. 将多个foreach循环存储到一个数组中
- 25. 正在下载将图像解析为数组,然后将它们追加到另一个数组中
- 26. 存储一个对象到数据库,然后再次检索它
- 27. 取出一串字符串并将它们存储在一个数组中
- 28. 数组列表存储到在c#另一个数组列表
- 29. 将整数和数组存储在一个文件中并读取它们
- 30. PHP - 计数$ _POST项目并将它们存储在一个数组中
这是一个任务,而不是一个问题。你有什么尝试?你面临什么问题? – Dmitry 2015-03-31 16:51:33
(你可能想使用LINQ与'Where',btw ...) – 2015-03-31 16:53:33
@JonSkeet如果他想要索引,他不会(在技术上他可以,因为哈比卜写的,但它是一个很大的弯路) – xanatos 2015-03-31 16:53:54