Development Desk

Just another WordPress.com site

Category Archives: LINQ

Filter Collections (same as ‘Like’ operator in SQL) by using LINQ

A simple collection of objects can easily be filtered by using LINQ rather than traversing through whole collection one by one in loops with the help of complex coding.
Whenever we are using a Like operator in SQL query we perform usually three types of operations with it.

1.    Like ‘abc%’ //grab those values in particular column only starting with abc
2.    Like ‘%abc%’ //grab those values in particular column which contains abc
3.    Like ‘%abc’  //grab only those values from particular column ending with abc

Though System.Data.Linq.SqlClient.SqlMethods name space has a Like() method to filter the data but it only supports to LINQ to SQL, so it can’t be used here

Lets go step by step beginning with 1. Filter Start with ( Like ‘b%’ )

1

I had the BookInformation Table in the Database i fetch all data from the table and then Filter that data according to requirement. In above code you can see, from all collection it will only show the data which is Starting with ‘b’. I filtered the whole collection by using the StartsWith() Method

Now lets go for 2nd Option, 2. Filter Contains ( Like ‘%or%’ )

1

in above code example in above code fetched all data from the database table and then Filter that data on the basis of Books name having ‘or’ in their names by using Contains()  Method

Finally, 3. Filter Ends with ( Like ‘%k’ )

3

in above code fetched all data from the database table and then Filter that data on the basis of Books name ending ‘K’ by using the EndsWith() method

 

Note: Pleas make sure all these filter method StartsWith(), Contains() and EndsWith() are case sensitive mean if suppose the name of the Book is “Border Force” and you are trying to fetch data on the base of “b” it will return nothing, So you should “B” for that.
You may need to convert filterCollection object to List or any other collection to bind

I hope this post will be helpful for you any queries please let me know

Thank your