Updated April 5, 2023
Introduction to LINQ Contains
LINQ Contains operator is used to make sure whether the specified value available in the collection of element or not. The LINQ Contains operator comes under the Quantifier operator category, the main purpose of this operator is used to check whether the specified element present in the collection or not, and finally it returns the boolean value as a result. LINQ Contains will not be supported in Query syntax it will be available only in the method syntax.
Syntax:
Let’s see the following syntax for LINQ-Contains, the Contains extension method available in two overloaded methods,
public static bool Contains<TSource>(this IEnumerable<TSource> source, TSource value);
Firstly the above overloaded method has a single argument and is used to check the element in the collection,
public static bool Contains<TSource>(this IEnumerable<TSource> source, TSource value, IEqualityComparer<TSource> comparer);
Where the second overloaded method requires the extra argument and is used for the complex type comparisons which contain the IEqualityComparer to check for any match in the properties of complex types.
How Contains Works in LINQ?
LINQ Contains is quantifier operator. In LINQ Contains it also checks with the data sources, to check whether the collection of lists contains their desired element or not, and then it returns the result as either true or false based on the expected outcomes of the result. LINQ Contains will not be supported in Query syntax it will be available only in the method syntax. Here when we using the complex types we go with the custom class which derives the IEqualityOperator with Contains to ensure the object is in the sequence/ collection.
Let’s see the working flow of LINQ-Contains in two overloaded methods now here see the first overloaded method as follows,
List<string> userNames=new List<string>();
userNames.Add("Neethu");
userNames.Add("Mithula");
userNames.Add("Naina");
userNames.Add("Neha");
Bool getResult=usernames.Contains("Mithun");
Console.WriteLine(getResult);
In the above code here we checking whether the given name is present or not in the list items, usernames.Contains(“Mithun”); it checks whether the names contains in it and returns the boolean result, the given username appeared in the list so it returns the result as “true”.
Now see the second overloaded method using LINQ-Contains with IEqualityComparer,
internal class user
{
public int userId { get; set; }
public string userName { get; set; }
public string userMobile { get; set; }
}
internal class UserNameComparer : IEqualityComparer<user>
{
public bool Equals(user x, user y)
{
if (string.Equals(x. userName, y. userName, StringComparison.OrdinalIgnoreCase))
{
return true;
}
return false;
}
public int GetHashCode(user obj)
{
return obj.userName.GetHashCode();
}
}
public class Program
{
public static void Main(string[] args)
{
List<user> userList = new List<user>();
userList.Add(new user { userId = 1001, userName = "Sarav", userMobile = "9004889002" });
userList.Add(new user { userId = 1002, userName = "David", userMobile = "9900887654" });
userList.Add(new user { userId = 1003, userName = "Vicky", userMobile = "9500213461" });
userList.Add(new user { userId = 1004, userName = "Gio", userMobile = "9909983222" });
var getUser = new user { userName = "Sarav" };
var Check_Result = userList.Contains(getUser, new UserNameComparer ());
Console.WriteLine(Check_Result);
}
}
In the above code we have built the complex type user list collection, we included a number of users in user collection to check whether the specific user name exists in the sequence of the users list, and also we have created the class UserNameComparer implements the IEqualityComparer<user> interface.
IEqualityComparer interface which contains the two methods called the Equals and GetHasCode, both the methods are very important to implement for getting an accurate result. In the Equals method we matching the username property and in the GetHashCode method, it only returns the hash code of the name property.
var getUser = new user { userName = "Sarav" };
var Check_Result = userList.Contains(getUser, new UserNameComparer ());
In the above code we have created the new class for the user and load only the name property which passing the UserNameComparer to the second parameter of Contains method, and then Contains operator used the Equals and GetHashCode of UserNameComparer class for the comparison of the name property to find out the exact user. It returns true as the result.
Examples of LINQ Contains
In this sample code we have built the complex type product list, we included a number of products listing with several attributes, here we have to check whether the product name exists in the collection, and also we have created the class ProductNameComparer implements the IEqualityComparer<productclass> interface.
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Console_LINQContains
{
class ProductClass
{
public int _productID {get; set;}
public string _productCategory { get; set; }
public string _productName { get; set; }
public int _productCost { get; set; }
}
internal class ProductNameComparer : IEqualityComparer<ProductClass>
{
public bool Equals(ProductClass x, ProductClass y)
{
if (string.Equals(x._productName, y._productName, StringComparison.OrdinalIgnoreCase))
{
return true;
}
return false;
}
public int GetHashCode(ProductClass obj)
{
return obj._productName.GetHashCode();
}
}
public class Program
{
static void Main(string[] args)
{
// adding the product details List
IList<ProductClass> _productList = new List<ProductClass>();
_productList.Add(new ProductClass { _productID = 1001, _productCategory = "Electronics", _productName = "Speakers", _productCost = 2880 });
_productList.Add(new ProductClass { _productID = 1002, _productCategory = "Electronics", _productName = "Graphics-Card", _productCost = 3000 });
_productList.Add(new ProductClass { _productID = 1003, _productCategory = "Electronics", _productName = "KeyBoard", _productCost = 1540 });
_productList.Add(new ProductClass { _productID = 1004, _productCategory = "Electronics", _productName = "Pendrive", _productCost = 475 });
_productList.Add(new ProductClass { _productID = 1009, _productCategory = "Stationery", _productName = "A4 Sheet Bunddle", _productCost = 100 });
_productList.Add(new ProductClass { _productID = 1010, _productCategory = "Stationery", _productName = "Pencil Box", _productCost = 52 });
_productList.Add(new ProductClass { _productID = 1011, _productCategory = "Stationery", _productName = "Ink-Bottle", _productCost = 45 });
_productList.Add(new ProductClass { _productID = 1012, _productCategory = "Stationery", _productName = "NoteBooks", _productCost = 75 });
var getProductName = new ProductClass { _productName = "Speakers" };
var containsResult = _productList.Contains(getProductName, new ProductNameComparer());
Console.WriteLine("LINQ-CONTAINS");
Console.WriteLine("-------------\n");
Console.WriteLine(containsResult);
Console.WriteLine("-------------\n");
Console.ReadKey();
}
}
}
In this, we checking whether the given name is present in the list items, _productList.Contains(getProductName, new ProductNameComparer()); it checks whether the names contains in it and returns the booloean result, the given username appeared in the list so it returns the result as “true”. Let’s see the output as follows.
Output:
Conclusion
The article is explained about the purpose of LINQ-Contains which is used to check whether the specific elements present in the collection; when working on complex types we need to implement IEqualityComparer interface to retrieve the exact results. Hope the article helps you to understand the needs of the LINQ-Contains with example programmatically.
Recommended Articles
This is a guide to LINQ Contains. Here we also discuss the introduction and how contains works in LINQ? along with an example. You may also have a look at the following articles to learn more –