"WHERE OR" in LINQ using "Contains"
In on of my recent implementations I was looking to loop through a series of categories and then find all the jobs in those categories and add them to a the results list. The most logical way of doing this would have been to "Where OR" a bunch of items together. LINQ however does not contain a "WhereOr" operator. Instead I was able to implement by 1) shoving the selected items into an integer array, and then 2) Using the "Contains" command to filter down the job/category link table.
Here's a code snippet:
'If the category selection method is selected then filter the jobs. If rblCategories.SelectedValue = "Some" Then 'Get all the categories and throw them into an array. Dim CategoryIdList As New ArrayList() For Each li As ListItem In cblCategories.Items If li.Selected Then Dim intCategoryId As Integer = li.Value CategoryIdList.Add(intCategoryId) End If Next 'Cast the array list into the an array of integers Dim intCategoryIdList As Integer() = CType(CategoryIdList.ToArray(GetType(Integer)), Integer()) 'Filter the category List Dim categories = From c In dbCareerServices.LQ_TBL_JOBS_TO_CATEGORies Select c categories = categories.Where(Function(ct) intCategoryIdList.Contains(ct.int_category_id)) 'Now filter the job list result = result.Where(Function(j) categories.Any(Function(c) c.int_job_id = j.int_job_id)) End If
If anyone knows of a better way to get similar results with LINQ, please let me know.















2 Comments, Comment or Ping
Alain
Hey there,
Thanks for the post. Was just about to do what you did but stumbled across this. Seems too simple to work (not sure why I didn't try), but I believe it does exactly what you need as well.
It's been a couple years since you posted this, but perhaps it could still come in handy.
Alain
Oct 20th, 2010
Alain
The link would have been helpful, I'm sure:
http://stackoverflow.com/questions/2101540/linq-or-equivalent-of-where
collection.Where( c => c.A == 1 || c.B == 2 );
Oct 20th, 2010
Reply to “"WHERE OR" in LINQ using "Contains"”