从C#中的unqiue(独立)元素获取索引

时间:2019-10-22 09:36:02

标签: c#

我想获取独立元素的索引。元素本身有可能出现在列表中的频率更高(一个接一个或多个)。单个元素的指示是,前任和后继不等于当前元素。有没有一种优雅的方法可以做到这一点?

示例

1.  A
2.  A
3.  A
4.  B
5.  B
6.  A
7.  B
8.  B
9.  C
10. B

结果:

6,9,10

5 个答案:

答案 0 :(得分:4)

简单地遍历项目并检查条件

char[] items = { 'A', 'A', 'A', 'B', 'B', 'A', 'B', 'B', 'C', 'B' };
for (int i = 0; i < items.Length; i++)
{
    if (i == 0)
    {
        // in case of the first element you only have to validate against the next
        if (items[i] != items[i + 1])
            Console.WriteLine(i + 1);
    }
    else if (i == items.Length - 1)
    {
        // in case of the last element you only have to validate against the previous       
        if (items[i] != items[i - 1])
            Console.WriteLine(i + 1);
    }
    else
    {
        // validate against previous and next element
        if (items[i] != items[i - 1] && items[i] != items[i + 1])
            Console.WriteLine(i + 1);
    }
}

https://dotnetfiddle.net/kWmqu7

答案 1 :(得分:3)

这是即使输入序列不支持索引也可以在spring-boot时间内工作的解决方案。它也适用于实现适当的O(N)的任何类型:

Equals()

答案 2 :(得分:2)

这是我想出的一种解决方案:

因此,您的示例列表如下:

var list = new List<string>
{
    "A", // 1
    "A", // 2
    "A", // 3
    "B", // 4
    "B", // 5
    "A", // 6
    "B", // 7
    "B", // 8
    "C", // 9
    "B"  // 10
};

然后调用名为GetSingleListPositions的方法,并接收代表您所需位置的List<int>

private static List<int> GetSingleListPositions(IList<string> list)
{
    var uniquePositions = new List<int>();
    var occurence = new List<string>();

    for (int i = list.Count - 1; i >= 0; i--)
    {
        if (!occurence.Contains(list[i]))
        {
            occurence.Add(list[i]);
            uniquePositions.Add(++i);
        }
    }

    uniquePositions.Reverse();
    return uniquePositions;
}

您这样称呼它:

var result = GetSingleListPositions(list);
Console.WriteLine(string.Join(' ', result));

结果,我收到了这个消息:

6 9 10

希望这会有所帮助, 干杯

答案 3 :(得分:0)

假设您要元素的最后一个索引。尝试下面的代码。

    string[] abc = new string[]{"A","A","A","B","B","A","B","B","C","B"};

    var distinctValues = abc.Distinct().Select(x => x);
    foreach (var d in distinctValues)
    {
        Console.WriteLine(Array.LastIndexOf(abc.ToArray(), d));
    }

//Result
5
9
8

答案 4 :(得分:0)

using System.Linq;
using System;

Add your namespace and class

**variables needed**
string[] printer = {"A", "A", "A", "B", "B","A","B","B","C","B"};
int[] terms = new int[10];
int check=0;
 int index1=0;
**method to check the value present in array and add index if not present in array for your output**

for (int i = i; i <= printer.Length; i++)
{
   int test=findIndex(i,printer.Length,printer[i]);
if(test==0)
{
  addIndex(i);
}
}
**method to addindex delare**

public addIndex(int num)
{
    terms[index1] = value;
    index1=index1+1;

}
**method to findIndex**

public int findIndex(int num1, int num2,string test) {
for (int i = num1; i < num2; i++)
{
    if (string.Compare(printer[i],test)==0 )
        {
            return 1;
       }

}
    return 0;

}