Reputation: 19
Instead of removing the first occurrence of a duplicated value, as my code currently does, how can I get it to delete the second occurrence instead?
namespace deletenumber
{
class Program
{
public static void Main(String[] args)
{
Random r = new Random();
int[] a = new int[10];
for (int i = 0; i < 10; i++)
a[i] = r.Next(1, 100);
for (int i = 0; i < 10; i++)
Console.WriteLine(" a [" + i + "] = " + a[i]);
Console.WriteLine();
Console.ReadLine();
Console.WriteLine("What number do you want to delete?");
int item = Convert.ToInt32(Console.ReadLine());
Console.WriteLine();
int index = Array.IndexOf(a, item);
a = a.Where((b, c) => c != index).ToArray();
Console.WriteLine(String.Join(", ", a));
Console.ReadLine();
}
}
}
Upvotes: 0
Views: 554
Reputation: 8330
I'm not sure why exactly you might want to delete only the second occurrence because there should be no matter which one of the duplicates is removed, correct?
Anyway, there are several ways of achieving what you want. I will not directly write a solution here, but will propose the methods you can use in order to achieve what you want:
IndexOf
method again to find the second occurrence, by starting the search from the previous occurrence (myArray.IndexOf("string", last_indexof_index);
)Generally, consider using a HashSet<T>
(official docs here) if you want to have a collection of unique elements.
You can also convert your existing collection to HashSet<int>
:
int[] a = new int[10];
var set = new HashSet<int>(a);
Upvotes: 1
Reputation: 261
You could convert your array to a List and then just remove the index before casting it back to an array:
var list = new List<int>(a);
list.RemoveAt(index);
a = list.ToArray();
Upvotes: 1