使用String获取ArrayList中的每个indexOf

时间:2015-11-04 18:49:08

标签: c# arraylist indexof

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

3 个答案:

答案 0 :(得分:1)

尝试以下方法:

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实现),您可能必须修改相等性检查。

答案 1 :(得分:0)

Non 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;
}

答案 2 :(得分:0)

var results = yourList.Cast<Fruit>()
                      .Select((fruit, index) => fruit.Name == "apple" ? index : -1)
                      .Where(elem => elem >= 0)
                      .ToList();
相关问题