C# List Contains

Description

List Contains determines whether an element is in the List .

Syntax


public bool Contains(
  T item
)

Parameters

  • item - The object to locate in the List . The value can be null for reference types.

Returns

List.Contains method returns true if item is found in the List; otherwise, false.

Example


using System;/*w  w  w  .j  av 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 »
    System.Collections.Generic »




HashSet
LinkedList
LinkedListNode
List
Queue
SortedSet
Stack