List Class


I have implemented a class that is a list:

Public class CompareItems
      Public string type {get; set; }
      Public int item1 { get; set; }
      Public int item2 { get; set; }

Public List< CompareItems> compareJobList = new List< CompareItems>();

I can populate this okay, but I now have a requirement to check that the list does not accept duplicate values.  I know this could be done on normal list by using the contains function.

However can it be done on this type of a list?

So I would need to check all 3 values don't exist?
Who is Participating?
Göran AnderssonConnect With a Mentor Commented:
To be able to check if an item is in a collection, you need to be able to compare them. The default comparison for objects only compares the references, so if you have two objects with the exact same values, they will still not be equal.

Implement the IEquatable<T> interface for the class:

public class CompareItems : IEquatable<CompareItems> {
	public string type { get; set; }
	public int item1 { get; set; }
	public int item2 { get; set; }

	public bool Equals(CompareItems other) {
		return type == other.type && item1 == other.item1 && item2 == other.item2;


Open in new window

Now you can check if an item exists in the list. In this example, only the first item will be added to the list:

CompareItems item1 = new CompareItems { type = "test", item1 = 42, item2 = 1337 };
if (!compareJobList.Contains(item1)) {

CompareItems item2 = new CompareItems { type = "test", item1 = 42, item2 = 1337 };
if (!compareJobList.Contains(item2)) {

Open in new window

If you're using .NET 3.5 or later, LINQ is the answer to this one:
compareJobList .Where(t => t.item1 == 3);
if  less .net 3.5
compareJobList .Exists(t => t.item1 == 3&& t.item2=1)
compareJobList .FindAll(t => t.item1 == 3&& t.item2=1)
käµfm³d 👽Commented:
If you're using .NET 3.5 or later, LINQ is the answer to this one:
compareJobList .Where(t => t.item1 == 3);
I'd suggest Any instead of Where.

using System.Linq;


bool exists = compareJobList .Any(t => t.item1 == 3);

Open in new window

Jaime OlivaresSoftware ArchitectCommented:
Instead of a List<> you can use a HashSet<> (
A hashset will never store a duplicate
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.