我想要得到一个数组的索引,我已经用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. PHP从多维数组中找到值,然后将它们放在一个数组中
- 4. 将数组存储在另一个数组中C
- 5. 在一个数组中输入Floats然后将它们加在一起
- 6. 如何在Zend Lucene中将一个数组数组存储到一个索引文档中?
- 7. 使用它们的索引号一次对多个数组进行排序?
- 8. 一维数组中的多个索引
- 9. 索引一个索引数组的多维numpy数组
- 10. 存储一个对象到数据库,然后再次检索它
- 11. 我想从用户那里得到所需的整数数量并将它们存储到一个数组中
- 12. 取出一串字符串并将它们存储在一个数组中
- 13. 数组列表存储到在c#另一个数组列表
- 14. PHP - 计数$ _POST项目并将它们存储在一个数组中
- 15. 获取一个随机数组的索引,然后使用相同的索引来打印另一个数组
- 16. 在一个单独的数组中排序数组和存储索引
- 17. 如何分配多个值一次到多维数组后创建它 - 在C?
- 18. 将数组和对象存储到另一个数组中
- 19. 如何将随机数组值一起添加到另一个数组中,然后在计数出现多少个值时显示它们? C++
- 20. 计数日历周,并将它们存储到一个数组与.isocalendar
- 21. 将索引存储在数组中
- 22. 将数据存储在数组中 - 然后迭代该数组
- 23. javascript:将多个变量存储在一个数组中
- 24. 得到一个列的值,并将其存储到一个数组 - DataGridView的
- 25. 在数组中添加一个数组到一个数组中的多个根
- 26. 从另一个数组索引中获得数组值
- 27. 数组索引存储在新数组
- 28. 如何将多个数组组合到一个新数组中?
- 29. 抢选定的图像ID,并将它们存储到一个int数组
- 30. 移动/移动数组中的对象,然后将第一个元素移动到最后一个索引
这是一个任务,而不是一个问题。你有什么尝试?你面临什么问题? – Dmitry 2015-03-31 16:51:33
(你可能想使用LINQ与'Where',btw ...) – 2015-03-31 16:53:33
@JonSkeet如果他想要索引,他不会(在技术上他可以,因为哈比卜写的,但它是一个很大的弯路) – xanatos 2015-03-31 16:53:54