英文:
Get the list of index for a string in an array?
问题
我有一个数组:
string[] cars = { "Volvo", "BMW", "Volvo", "Mazda", "BMW", "BMW" };
我想要查找 "BMW" 的索引,我使用以下代码来获取:
Label1.Text = Array.FindAll(cars, x => x.Contains("BMW"))
.Select((value, index) => index)
.ToArray();
不幸的是,它只返回第一个 "BMW" 的索引。
当前输出:
1
我期望的输出将是:
[1, 4, 5]
英文:
I have one array:
string[] cars = {"Volvo", "BMW", "Volvo", "Mazda","BMW","BMW"};
I m looking for the index of BMW, and I using below code to get:
Label1.Text = Array.FindIndex(filterlistinput, x => x.Contains("BMW")).ToString();
Unfortunately it return the result for the first BMW index only.
Current output:
1
My expected output will be
{1,4,5}
答案1
得分: 9
string[] cars = { "Volvo", "BMW", "Volvo", "Mazda", "BMW", "BMW" };
// 获取 BMW 的索引
var indicesArray = cars.Select((car, index) => car == "BMW" ? index : -1).Where(i => i != -1).ToArray();
// 显示索引
Label1.Text = string.Join(", ", indicesArray);
英文:
You can do something as follows
string[] cars = { "Volvo", "BMW", "Volvo", "Mazda", "BMW", "BMW" };
// Get indices of BMW
var indicesArray = cars.Select((car, index) => car == "BMW" ? index : -1).Where(i => i != -1).ToArray();
// Display indices
Label1.Text = string.Join(", ", indicesArray);
答案2
得分: 4
你可以尝试以下内容:
string[] cars = { "Volvo", "BMW", "Volvo", "Mazda", "BMW", "BMW" };
// 作为列表返回 {1,4,5}
var res = Enumerable.Range(0, cars.Length).Where(i => cars[i] == "BMW").ToList();
// 以"1,4,5"的形式连接列表项
Label1.Text = string.Join(",", res);
英文:
You can try the following,
string[] cars = {"Volvo", "BMW", "Volvo", "Mazda","BMW","BMW"};
//returns **{1,4,5}** as a list
var res = Enumerable.Range(0, cars.Length).Where(i => cars[i] == "BMW").ToList();
//joined items of list as 1,4,5
Label1.Text = string.Join(",", res);
答案3
得分: 3
以下是翻译好的部分:
以这种方式使用它:
string[] cars = { "Volvo", "BMW", "Volvo", "Mazda", "BMW", "BMW" };
var indexes = cars.FindIndexes(s => s.Equals("BMW")).ToArray();
// 返回 1, 4, 5
英文:
Previous answers are also ok. But I would do it like this if you need to do a lot of similar index searches. Will reduce the amount of code you write in the long term.
public static class SequenceExt
{
public static IEnumerable<int> FindIndexes<T>(this IEnumerable<T> items, Func<T, bool> predicate)
{
int index = 0;
foreach (T item in items)
{
if (predicate(item))
{
yield return index;
}
index++;
}
}
}
use it like this:
string[] cars = { "Volvo", "BMW", "Volvo", "Mazda", "BMW", "BMW" };
var indexes = cars.FindIndexes(s => s.Equals("BMW")).ToArray();
> returns 1,4,5
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论