Contains

suggest change

MSDN:

Determines whether a sequence contains a specified element by using a specified IEqualityComparer<T>

List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
var result1 = numbers.Contains(4); // true
var result2 = numbers.Contains(8); // false

List<int> secondNumberCollection = new List<int> { 4, 5, 6, 7 };
// Intersect can express the same filter.
var result3 = secondNumberCollection.Where(item => numbers.Contains(item)); // 4 and 5

Using a user defined object:

public class Person
{
   public string Name { get; set; }
}

List<Person> objects = new List<Person>
{
    new Person { Name = "Nikki"},
    new Person { Name = "Gilad"},
    new Person { Name = "Phil"},
    new Person { Name = "John"}
};

// Person does not override Equals or GetHashCode, so this compares references.
var result4 = objects.Contains(new Person { Name = "Phil" }); // false

Using the Enumerable.Contains(value, comparer) overload:

public class Compare : IEqualityComparer<Person>
{
    public bool Equals(Person x, Person y)
    {
        return x.Name == y.Name;
    }
    public int GetHashCode(Person codeh)
    {
        return codeh.Name.GetHashCode();
    }
}

var result5 = objects.Contains(new Person { Name = "Phil" }, new Compare()); // true

Contains can replace a chain of equality tests.

So instead of doing this:

if(status == 1 || status == 3 || status == 4)
{
    //Do some business operation
}
else
{
    //Do something else
}

Do this:

if (new int[] { 1, 3, 4 }.Contains(status))
{
    //Do some business operation
}
else 
{
    //Do something else
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents