如何从C#中的数组中获取重复项中最新元素的索引? [英] how to get index of latest element among duplicate items from array in c#?

查看:142
本文介绍了如何从C#中的数组中获取重复项中最新元素的索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

我有一个包含重复值的数组.现在我想要该数组的索引的另一个数组,其中包含所有非重复元素的索引+重复项的最新索引.

int [] arr = {1,1,2,2,3,4,5,6,6,7};

输出

int [] indexarr = {1,3,4,5,6,8,9}

其中1是第二个索引的1,3是最后一个2的索引,4是3的索引,依此类推..

Hi all,

i have an array which contains duplicate values. now i want an other array of the indexes of the array with all the index of non repeat element + latest index of the duplicate items.

int [] arr = {1,1,2,2,3,4,5,6,6,7};

output

int[] indexarr = {1,3,4,5,6,8,9}

where 1 is the index of second 1,3 is the index of last 2, 4 is the index of 3 etc..

推荐答案

ravikhoda,

使用LINQ的好问题:

这是一个小样例程序

Hi ravikhoda,

Good Problem to use LINQ:

Here is a Little sample program

using System;
using System.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] aNumbers = { 1, 1, 2, 2, 3, 4, 5, 6, 6, 7 };

            var indices = from number in aNumbers.Distinct()
                             select aNumbers.ToList().LastIndexOf(number);
            int[] aIndices = indices.ToArray();

            foreach (int iIndex in aIndices)
                Console.WriteLine(iIndex);

            Console.ReadKey();
        }
    }
}


这个想法是只从原始数组中选择不同的值.然后,我们为原始数组上的每个不同的数字调用LastIndexOf .通过此表达式,我们可以建立索引的IEnumerable.这将转换为所需的整数输出类型数组(不需要像上面的示例中那样进行枚举).

希望这会有所帮助

亲切的问候约翰内斯


The idea is to select only the distinct values from the original array. Then we call LastIndexOf for every distinct number on the original array. By this expression we build a IEnumerable of our indices. This is converted to your desired array of integers output-type (would not be needed just for enumerating like in the above sample).

Hope this helps

Kind regards Johannes


这篇关于如何从C#中的数组中获取重复项中最新元素的索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆