Contains

In this chapter you will learn:

  1. Use Contains operator
  2. Contains with string value
  3. Contains with string value and IEqualityComparer

Use Contains operator

Contains returns true if the given element is present:

using System;/* j  a v a  2 s  .c o m*/
using System.Collections;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        bool hasAThree = new int[] { 2, 3, 4 }.Contains(3); // true;

        Console.WriteLine(hasAThree);
    }
}

The output:

Contains with string value

using System;/*  java2  s.  co m*/
using System.Linq;
using System.Collections;
using System.Collections.Generic;

public class MainClass {
    public static void Main() {
        string[] presidents = {"G", "H", "a", "java2s.com", "over", "Jack"};

        bool contains = presidents.Contains("java2s.com");
        Console.WriteLine(contains);
    }
}

Contains with string value and IEqualityComparer

using System;/* java  2  s .  com*/
using System.Linq;
using System.Collections;
using System.Collections.Generic;
public class MyStringifiedNumberComparer : IEqualityComparer<string> {
    public bool Equals(string x, string y) {
        return (Int32.Parse(x) == Int32.Parse(y));
    }

    public int GetHashCode(string obj) {
        return Int32.Parse(obj).ToString().GetHashCode();
    }
}
public class MainClass {
    public static void Main() {
        string[] stringifiedNums = {"001", "49", "017", "0080", "00027", "2" };
        bool contains = stringifiedNums.Contains("000271",new MyStringifiedNumberComparer());
        Console.WriteLine(contains);
    }
}

Next chapter...

What you will learn in the next chapter:

  1. How to count with count operator
  2. Count with filter delegate
  3. supply a predicate
  4. Count with string operator
  5. Count distinct values
Home » C# Tutorial » Linq Operators
Aggregate
Aggregate with seed
Aggregate string value
All
Any
Average
Cast
Concat
Contains
Count
DefaultIfEmpty
Distinct
ElementAt
ElementAtOrDefault
Empty
Except
FindAll
First
FirstOrDefault
GroupBy
Intersect
Last
LastOrDefault
LongCount
Max
Min
OfType
OrderBy
OrderByDescending
Range
Repeat
Reverse
SelectMany
SequenceEqual
Single
SingleOrDefault
Skip
SkipWhile
Sum
Take
TakeWhile
ThenBy
ThenByDescending
ToArray
ToList
Zip