user3488765 user3488765 - 1 year ago 74
C# Question

Add each last occurence of object to list ordered by most recent addition

I need a logger of sorts and have to dump the contents from time to time.
I want to get only the last instance of each item and preserve that order.

Is there a better way to do it than like this? List.contains is to expensive, but I'm not happy with the memory overhead of the extra hashset aswell.

public List<Int3> UnsafeDumpMostRecentUsageLast() {

HashSet<Int3> _containsHelper = new HashSet<Int3>();
List<Int3> uniqueOccurencesOrdered = new List<Int3>(uniqueConsumedCount);

for (int i = usageLog.Length-1;i >= 0; i--) {

if (_containsHelper.Add(usageLog[i]))

return uniqueOccurencesOrdered;

To clear it up.. say I have a list like this:


I want to return a list that returns the uppercases:


So the list would be: BEDAC



Answer Source

I am not sure what Int3 type is, but if we assume we are talking about an int (works similarly in other cases) and usageLog is an IEnumerableyou could do the following:

public List<Int3> UnsafeDumpMostRecentUsageLast() {          
    return usageLog.Distinct().ToList();


If your list is already sorted and you just want to keep the last occurrence of each instance (like your comment suggests) :