简体   繁体   English

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

[英]Getting index from unqiue (stand-alone) elements in C#

I'd like to get the index of elements that stand alone.我想获得独立元素的索引。 It is possible that the elements themselves appear more often in the list (one after the other or mixed).元素本身可能更频繁地出现在列表中(一个接一个或混合出现)。 The indication for a single element is that the predecessor and successor are not equal to the current element.单个元素的指示是前任和后继不等于当前元素。 Is there an elegant way to do this?有没有一种优雅的方式来做到这一点?

Example :示例

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

Result:结果:

6,9,10

simple iterate over the items and check for that condition简单地遍历项目并检查该条件

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 https://dotnetfiddle.net/kWmqu7

Here's a solution that works in O(N) time even if the input sequence does not support indexing.这是一个即使输入序列不支持索引也能在O(N)时间内工作的解决方案。 It also works for any type that implements a proper Equals() :它也适用于实现适当Equals()的任何类型:

public static IEnumerable<int> IndicesOfStandaloneElements<T>(IEnumerable<T> elements)
{
    int index = 0;

    T previous = default;
    T current  = default;

    var comparer = EqualityComparer<T>.Default;

    foreach (var next in elements)
    {
        if (index == 1)
        {
            if (!comparer.Equals(current, next))
                yield return 0;
        }
        else if (index > 1)
        {
            if (!comparer.Equals(current, previous) && !comparer.Equals(current, next))
                yield return index - 1;
        }

        previous = current;
        current  = next;

        ++index;
    }

    if (index > 0 && !comparer.Equals(current, previous))
        yield return index - 1;
}

Here is one solution I came up with:这是我想出的一种解决方案:

So you have your example list like that:所以你有这样的示例列表:

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

and then you call a method called GetSingleListPositions and receive List<int> representing your desired positions.然后你调用一个名为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;
}

You call it like this:你这样称呼它:

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

As a result, I receive this:结果,我收到了这个:

6 9 10

Hope this helps, Cheers希望这会有所帮助,干杯

You can achieve it using the Dictionary<string, int>您可以使用Dictionary<string, int>来实现它

var list = new List<string> { "A", "A", "A", "B", "B", "A", "B", "B", "C", "B" };

var dict = new Dictionary<string, int>();
for (int i = 0; i < list.Count; i++)
{
        if (dict.ContainsKey(list[i]))
            dict[list[i]] = i + 1;
        else
            dict.Add(list[i], i + 1);
}

dict.Values contains the required indices dict.Values包含所需的索引

Assuming that you want last index of the elements.假设您想要元素的最后一个索引。 Try below code.试试下面的代码。

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

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM