从包含可能重复项的列表中获取特定项的索引

本文关键字:获取 索引 列表 包含可 | 更新日期: 2023-09-27 18:01:43

好吧,我有一个类对象列表,如下所示:

List<fruit> lst = new List<fruit>();
    lst.Add(orange);
    lst.Add(apple);
    lst.Add(grape);
    lst.Add(grape);
    lst.Add(orange);
    lst.Add(pear);
    lst.Add(apple);

我想问一下清单GetIndex("orange",2(,并让它返回(在本例中(所讨论对象的第二个实例(位置4(的索引#。

这个列表将被动态填充,它甚至可能一开始就没有橙色。如果是,我需要第二个参数的实例号。所以我可以得到第二个橙子,或者第五个芒果,等等。

list.IndexOf(橙色(返回任何重复项的第一个实例,所以我需要其他东西。

有什么想法吗?

PS:我没有提到第一个参数将是字符串!

从包含可能重复项的列表中获取特定项的索引

public static int GetIndex<T>(this IEnumerable<T> lst, T obj, int index)
{
    return lst.Select((o, i) => new { o, i })
              .Where(x => x.o.Equals(obj))
              .ElementAt(index - 1)
              .i;
}

虽然index从1开始有点奇怪,但结果从0开始。

下面是我刚刚写的一个通用扩展搜索:

public static class ListExtension
{
    public static int GetIndex<T>(this List<T> entity, T what, int find)
    {
        int found = 0;
        int index = -1;
        while ((index = entity.IndexOf(what, (index + 1))) != -1)
        {
            found++;
            if (found == find)
                break;
        }
        return (index);
    }
}

你所要做的就是这样称呼它:

int index = lst.GetIndex(apple, 2);

如果找不到您要查找的项目,则返回-1。

        int index = lst.IndexOf(orange);
        if (index >= 0)
        {
            index = lst.IndexOf(orange, index + 1);
        }

或者为了使其通用,您可以使用一些LINQ:

    static int GetIndex(IEnumerable<Fruit> li, Fruit ob, int k)
    {
        var tmp = li.Select((it, i) => new Tuple<int, Fruit>(i, it)).Where(tup => tup.Item2 == ob).Skip(k - 1).FirstOrDefault();
        if (tmp == null)
            return -1;
        else 
            return tmp.Item1;
    }

然后调用GetIndex(lst, orange, 2)

您可以用自己的方法为该类扩展类,遗憾的是,这对于泛型类来说是不可能的,因此您可以用方法给出类型。

public static class ListExtension
{
    public static int GetIndex<T>(this List<T> list, T value, int skipMatches = 1)
    {
        for (int i = 0; i < list.Count; i++)
            if (list[i].Equals(value))
            {
                skipMatches--;
                if (skipMatches == 0)
                    return i;
            }
        return -1;
    }
}
List<int> list = new List<int>();
list.Add(3);
list.Add(4);
list.Add(5);
list.Add(4);
int secondFour = (int)list.GetIndex(4, 2);
var result = list.Select((x, i) => new { x, i })
                  .Where(t => t.x == fruit)
                  .Skip(k - 1)
                  .Select(t => t.i)
                  .First();

当你找不到你想要的值时,dtb答案的扩展:

public int GetIndex<T>(IEnumerable<T> list, T item, int itemNum) {
    // result is a nullable int containing the index
    var result = list.Select((x, i) => new { x, i })
                     .Where(t => item.Equals(t.x))
                     .Skip(itemNum - 1)
                     .Select(t => (int?)t.i)
                     .FirstOrDefault();
    // return -1 when item was not found
    return (result.HasValue ? result.Value : -1);
}