Learn how to use LINQ Contains method in c# linq Query !
IEnumerable.Contains method returns a Boolean value, search for given value in any object or collection, if found returns true.
Let's learn how to write Contains operator in Linq query
In following string array we check if there is word "Calcutta"
string[] placeArray = { "Calcutta", "Canada", "Costarica", "California", "Cameron", "Coimbatore" }; bool result = placeArray.Contains("Calcutta"); Console.WriteLine(result); // true
We also can check if any particular object is there in the collection
Now in this example we try to check a complex object type student, we check if there is any student with name “Ajay” in the student list.
We need to use IEqualityComparer to compare with any complex object, so first we have to create a custom class that will inherit from IEqualityComparer.
internal class StudentNameComparer : IEqualityComparer<Student> { public bool Equals(Student x, Student y) { if (string.Equals(x.FullName, y.FullName, StringComparison.OrdinalIgnoreCase)) { return true; } return false; } public int GetHashCode(Student obj) { return obj.FullName.GetHashCode(); } }
Now from the below student list we check if the list contains any student with name "Ajay" using above StudentNameComparer class.
var studentsStream = new List<Student> { new Student { FullName = "Aruna", StreamId=1, Score = 10 }, new Student { FullName = "Janet", StreamId=2, Score = 9 }, new Student { FullName = "Ajay", StreamId=1, Score = 11 }, new Student { FullName = "Kunal", StreamId=2, Score = 13 }, new Student { FullName = "Chandra", StreamId=2, Score = 8 }, }; bool result = studentsStream.Contains(new Student() { FullName = "Ajay" }, new StudentNameComparer()); Console.WriteLine(result); // true
Notice, whenever you use Contains method, after that you must use ToList or FirstOrDefault method to convert the entire object to a list or single object.