Question

I have a table that has multiple columns, one of which contains pipe separated values.

I found an answer that's partially what I'm looking for here but that assumes you're searching in one CSV-type list.

What I have is rows of data, one column (called serviceIDs) has data like 2|45|5|6

I want to be able to pass a value into a query something like this:

Select all rows where serviceIDs contains '5' 

or

Select all rows where serviceIDs like '%5%' 

But obviously neither of those are going to work properly. Is there a way to do this in LINQ?

Was it helpful?

Solution

Unfortunately Split isn't supported in LINQ to SQL. You could do something like the following where you tack on a leading and trailing pipe and then use contains with the leading and trailing pipe. That would solve the issue where finding 45 when searching for 5. Be aware that this could kill your performance because the calculated column value would block index usage in the database. If you store the original values with the leading and trailing pipe, the indexing would be better (but not as good as using a full text search).

var yourvalue = "5";
var expectedResult = "|" + yourvalue + "|";
var resultset = rows.Where(row => ("|" + row.serviceIDs + "|").Contains(expectedResult); 

OTHER TIPS

var yourvalue = "5";
var resultset = rows.Where(row => row.serviceIDs.Split('|').Contains(yourvalue));

disclaimer: i never used linq for DB stuff, but something along these lines might work

 yourTable.AsEnumerable()
.Select(row => row["serviceIDs"].ToString().Split('|'))
.ToList()
.Where(s => s == 5);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top