In a SQL Query, one might use the Like Query which can be used along with the % operator to search of contains within the data. How to use SQL like Operator in LINQ and C#? This article will show it with a sample code snippet.
How to use SQL like Operator in LINQ and C#?
Below is a sample source code demonstrating the usage of Contains extension method which returns the same results like the SQL “Like” operator.
using System; using System.Collections.Generic; using System.Data; using System.Linq; namespace AbundantCode { internal class Program { //How to use SQL Like Operator in LINQ and C# ? private static void Main(string[] args) { List<CodeSnippet> snippets = new List<CodeSnippet>() { new CodeSnippet { Code = "1" , Name = "Abundantcode1"}, new CodeSnippet { Code = "2" , Name = "Abundantcode2"}, new CodeSnippet { Code = "3" , Name = "Abundantcode1"}, new CodeSnippet { Code = "4" , Name = "Abundantcode2"}, new CodeSnippet { Code = "5" , Name = "Abundantcode4"} }; var data = (from m in snippets where m.Name.Contains("code2") select m); foreach (var item in data) Console.WriteLine(item.Name); Console.ReadLine(); } } public class CodeSnippet { public string Name { get; set; } public string Code { get; set; } } }
Leave a Reply