I implemented a search engine in my website that uses Linq-To-Sql. The output of the engine is a list of Result.
To increase security and performance, I’ve added a CachedResult table to my database. It had these columns:
ID, Date, Output
Where Output is a string which represents a list of integers which are the IDs for another table.
Using the Where method, I was able to extract those elements from the database. The problem is that their order is based on their order in the table, not the order of the integers in my string.
Therefore, I’ve added the OrderBy method this way:
db.Uploads.Where(upl => W.Contains(upl.UploadID)).OrderBy(pp => W.IndexOf(pp.UploadID));
W here is a list of integers (extracted from the database).
The probelm is that it throws an exception saying that the Linq-To-Sql translator cannot translate the List.IndexOf method to the appropriate SQL query.
I would like to know if I’m doing this right and there is a solution, or maybe I’m totally wrong and I must seek another way? (i.e making another table that has a relationship with CachedResults)
You can realise the result as a list before sorting, so that it uses Linq-To-Objects instead of Linq-To-Sql for the sorting:
However, that’s not very efficient. As the
IndexOfmethod is an O(n) operation, the sorting will be an O(n2) operation.Antother solution is to add another table
CachedResultItemsfor the integers for each cached result, containing fields like:Instead of storing a string like
5,7,12,26,81in theCachedResulttable, you would have these records in theCachedResultItemstable (for the ID 42 in theCachedResulttable):Then you can join the two tables, and sort the result on
Position.This would also be faster than first getting one result, splitting the string to a list, and use that list in a query, as it’s a single query, and it can use indexes more efficiently.