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
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With