Check if user defined element is in the List in CSharp

Description

The following code shows how to check if user defined element is in the List.

Example


using System;//ww  w . j a v a  2 s.  com
using System.Collections.Generic;

class Program
{
    static void Main(string[] args)
    {
        List<Box> boxes = new List<Box>();

        boxes.Add(new Box(8, 8, 4));
        boxes.Add(new Box(8, 4, 8));
        boxes.Add(new Box(8, 6, 4));

        if (boxes.Contains(new Box(8, 6, 4)))
        {
            Console.WriteLine("An equal box is already in the collection.");
        }
        else
        {
            Console.WriteLine("Box can be added.");
        }
    }
}

public class Box : IEquatable<Box>
{

    public Box(int h, int l, int w)
    {
        this.Height = h;
        this.Length = l;
        this.Width = w;
    }
    public int Height { get; set; }
    public int Length { get; set; }
    public int Width { get; set; }

    public bool Equals(Box other)
    {
        if (this.Height == other.Height && this.Length == other.Length
            && this.Width == other.Width)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
}

The code above generates the following result.





















Home »
  C# Tutorial »
    Collections »




ArrayList
BitArray
Collection
Comparer
HashSet
Hashtable
LinkedList
List
ListDictionary
OrderedDictionary
Queue
SortedList
SortedSet
Stack
StringCollection
StringDictionary