Help finding an item within a list

jmpatton used Ask the Experts™
I have a list of objects and before I add a new object to the list I need to see if it was already added.  I tried List.Items.Contains(), but it dodnt work.  Any help would be appreciated
CycleVolumeList cycleVolumeList = new CycleVolumeList();
cycleVolume = serviceClient.GetCycleVolume(Param1, Param2, Param3);

// Add it to cycleVolumeList
CycleVolume cycleVolume = new CycleVolume(item1, item2, cycleVolume );

                            if (cycleVolumeList.Items.Contains(new CycleVolume(item1, item2, cycleVolume)))
                              //do nothing  

Open in new window

Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
You need to compare objects by fields.

I.e. If you have an object Person that has fields Age, Sex, First Name, Last Name and you create it like so:
Person p1 = new Person ("John", "Doe", 27, "M");
Person p2 = new Person ("John", "Doe", 27, "M");

and then try to compare them like (p1 == p2), you will always get false as a result.

However, if you will query your list for any object where fields match, you might be in luck.

string fName = "John";
string lName = "Doe";
int age = 27;
string sex = "M";
List<Person> people = new List<Person>();

boolean wasFound = false;
foreach (Person p in people) 
  if (p.FirstName == fName && p.LastName == lName && p.Age == age && p.Sex == sex) {
    wasFound = true;
if (!wasFound) {
  people.Add(new Person(fName, lName, age, sex);

Open in new window

Hope this helps.




Thanks for the quick reply.  Much apprieciated!
Top Expert 2011

For Contains to work as you expect, CycleVolume must implement System.IEquatable<T>.

IEquatable<T> Interface (System)

I hope this helps.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial