blah blah blah is here! blah blah » Close

up1down
link

I want to have a list that will only contain unique entries. The uniqueness will be determined by a GUID. Here is what I was thinking...

interface LibraryListItem
{
Guid Guid { set; get; }
}

class LibraryList<T> : IEnumerable<T> where T : LibraryListItem
{
private List<T> libraryList = new List<T>();

public void Add(T t)
{
bool duplicate=false;

//Ensure unique
foreach (T temp in libraryList)
{
if (t.Guid == temp.Guid)
{
duplicate = true;
break;
}
}
if(!duplicate)
libraryList.Add(t);
}

IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
return libraryList.GetEnumerator();
}

IEnumerator IEnumerable.GetEnumerator()
{
return libraryList.GetEnumerator();
}

}


This way every time an item is added it is checked against what is currently in the list. Does this seem like a reasonable approach?

I don't know what to do if there is a duplicate. Perhaps this is a good point to generate an exception?

last answered one month ago

1 answers

link

Yes, that approach looks good to me provided that the List will not grow so large that the time taken to search for duplicates becomes significant.

I wouldn't throw an exception if you can avoid it. I'd either let the attempted addition of the duplicate fail silently as you're doing now or, if you really need to know whether the item was added, change your Add method so that it returns a bool - true if added, false if duplicated.

Incidentally, you need to check that the item to be added is not null, otherwise you will get an exception when you try to access the Guid property.

An alternative approach would be to use a Dictionary<Guid, LibraryListItem> rather than a custom List. This would automatically prevent you from adding an item with a duplicated key (i.e. Guid) though you'd then need to catch the exception generated by the Add() method.

However, if you're not really interested in keyed access - you just want to access elements by index - a Dictionary would not be suitable.

eeboy
335

A little off topic but where might I search for contractors who could build me a WPF/C# user interface for my project?

Feedback