I have a C# Array of objects that needs to stay in order that I'm trying to filter duplicates out of (not same object refference just same attribute values). The catch is the duplicate that has to go is the first one and the oldest needs to stay.
Current algorithm (semi pseudo code renamed everything) using IEnumerable
object[] filter(object[] array)
{
var set = new HashSet<Guid>();
var filtered = new List<object>();
for (int i = array.Length; i-- > 0;)
{
var item = array[i];
if (!set.Contains(item.ID))
{
set.Add(item.ID);
filtered = new List<object>(filtered.Prepend(item));
}
}
return filtered.ToArray();
}
I know it is currently O(n) but I am looking for a very efficient way of doing this. If possible with just arrays so I don't need to use .ToArray() and iterate again.
I could just make filtered an array of size array.length and put it in backwards i.e. "filtered[array.length-i] = item" but I don't want to have empty values.