In order to check if a class is already contained in a List, you need to implement IEquatable.
For example, I want to have class IDName added in to list, but, I don't want to have duplicates. Class:
class IDName: IEquatable<IDName>
{
public Guid ID { get; set; }
public string Name { get; set; }
public IDName (Guid id, string name)
{
ID = id;
Name = name;
}
public bool Equals(IDName other)
{
return ID == other.ID && Name == other.Name;
}
}
Program:
using System;
using System.Collections.Generic;
namespace Contains
{
class Program
{
static void Main(string[] args)
{
List<IDName> idNames = new List<IDName>();
Guid idFirst = Guid.NewGuid();
IDName idNameFirst = new IDName(idFirst, "first");
Guid idSecond = Guid.NewGuid();
IDName idNameSecond = new IDName(idSecond, "second");
idNames.Add(idNameFirst);
idNames.Add(idNameSecond);
if (idNames.Contains(idNameFirst))
{
Console.WriteLine("idNameFirst is already added");
}
Console.ReadKey();
}
}
}