I have a question:
Write a class that represents a sorted list of filenames. The filenames are sorted by most recently added first. Duplicates are not allowed.
And I wrote this solution:
public class RecentlyUsedList
{
private readonly List<string> items;
public RecentlyUsedList()
{
items = new List<string>();
}
public void Add(string newItem)
{
if (items.Contains(newItem))
{
int position = items.IndexOf(newItem);
string existingItem = items[position];
items.RemoveAt(position);
items.Insert(0, existingItem);
}
else
{
items.Insert(0, newItem);
}
}
public int Count
{
get
{
int size = items.Count;
return size;
}
}
public string this[int index]
{
get
{
int position = 0;
foreach (string item in items)
{
if (position == index)
return item;
++position;
}
throw new ArgumentOutOfRangeException();
}
}
}
Now, other person asked me, do the code review of your own code and tell the answers of following questions:
Three operations are required:
How long is the list?
Access filename at a given position
Add a filename to the list; if it already exists in the list it gets moved to the top otherwise the new filename is simply prepended to the top.
I got confused and tried to look on Google but I didn't get much from there. What would be the best answers to these questions?