使用字符串获取 ArrayList 中的每个 indexOf

Get every indexOf in ArrayList using a String

首先,我在 unity 中使用 c#。好的,我有一个 ArrayList。列出我们将称之为的项目。项目内容是 {apple, apple, berry, apple, nut};我想知道一种使用 items.indexOf(); 查找苹果所有索引号的方法;或其他一些功能。内容列表只是举例,在我使用的程序中,我实际上并不能确定内容,因为它们的大小和内容会有所不同。任何帮助将不胜感激。

尝试以下操作:

var result = list
    .Cast<TypeOfTheObjects>()                       // non-generic ArrayList needs a cast
    .Select((item, index) => new { Index = index, Item = item }) // select each item with its index
    .Where(x => apple.Equals(x.Item))               // filter
    .Select(x => x.Index)                           // select only index
    .ToList();

根据对象的类型(及其 Equals 实现),您可能需要修改相等性检查。

非 Linq 的实现方式:

private static List<int> Find(ArrayList items, string entry)
{
    var ret = new List<int>();
    for (var i = 0; i < items.Count; i++)
        if ((string) items[i] == entry)
            ret.Add(i);
    return ret;
}
var results = yourList.Cast<Fruit>()
                      .Select((fruit, index) => fruit.Name == "apple" ? index : -1)
                      .Where(elem => elem >= 0)
                      .ToList();