获取数组中字符串的索引列表?

Shi*_*Tio 6 c#

我有一个数组:

string[] cars = {"Volvo", "BMW", "Volvo", "Mazda","BMW","BMW"};
Run Code Online (Sandbox Code Playgroud)

我正在寻找宝马的索引,我使用下面的代码来获得:

Label1.Text = Array.FindIndex(filterlistinput, x => x.Contains("BMW")).ToString();
Run Code Online (Sandbox Code Playgroud)

不幸的是,它只返回第一个 BMW 指数的结果。电流输出:

 1
Run Code Online (Sandbox Code Playgroud)

我的预期输出将是

{1,4,5}
Run Code Online (Sandbox Code Playgroud)

Sha*_*hat 9

您可以执行以下操作

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);
Run Code Online (Sandbox Code Playgroud)


Fur*_*ürk 4

您可以尝试以下方法,

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);
Run Code Online (Sandbox Code Playgroud)