【问题标题】:Get every indexOf in ArrayList using a String使用字符串获取 ArrayList 中的每个 indexOf
【发布时间】:2016-02-05 09:53:46
【问题描述】:

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

【问题讨论】:

  • 为什么不遍历列表项?
  • 要更好地理解,请参阅dotnetperls.com/array-indexof
  • 我应该澄清一下,...我不一定知道物品的内容...我正在使用它来运行库存,...这将获得需要的物品事情,并且必须通过不同内容的许多不同的需求集......所以我不能使用假设我知道内容的方法。

标签: c# arraylist indexof


【解决方案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 实现),您可能需要修改相等检查。

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 我沉迷于使用 indexOf 或类似的方法,我什至没有考虑其他方法。谢谢。
    【解决方案3】:
    var results = yourList.Cast<Fruit>()
                          .Select((fruit, index) => fruit.Name == "apple" ? index : -1)
                          .Where(elem => elem >= 0)
                          .ToList();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-22
      • 2021-01-09
      • 1970-01-01
      • 2022-11-11
      • 2017-11-29
      相关资源
      最近更新 更多