views:

41

answers:

2

I'm trying to figure out how to allow a user to enter in a string of tags (keywords separated by spaces) in a textbox to filter a grid of results.

Here are the tables:


PACKETS
*PacketID
Name


PACKETTAGS
*PacketTagID
PacketID
TagID


Tags
*TagID
Name


Here is the basic query without the WHERE parameters:

SELECT     
       Packets.Name, Tags.Name AS Tag, PacketTags.PacketTagID
FROM         
       Packets 
INNER JOIN
       PacketTags ON Packets.PacketID = PacketTags.PacketID 
INNER JOIN
       Tags ON PacketTags.TagID = Tags.TagID

I need to filter out all the Packets that don't have tags that match any of the words BUT ALSO ONLY include the Packets that have the tags entered in the string of text (spaces separate the tags when entered into the textbox)

I'm starting with the basics by figuring this out in t-SQL first but ultimately I need to be able to do this in Linq-to-SQL

A: 

Assuming you have a list of your tags in memory:

var query = from p in DataContext.Packets 
            where p.Tags.Intersect(listOfMustHaveTags).Count() == listOfMustHaveTags.Count()
            select p;

I'm using intersect here to check the must-have tags set is fully contained. Maybe there's an even simpler solution.

Johannes Rudolph
Oh and btw. before anyone wonders: Intersect is supported by the L2S Linq provider.
Johannes Rudolph
I get this error when I use this the intersect like you suggest: Unable to cast object of type 'System.Collections.Generic.List`1[System.Guid]' to type 'System.Collections.Generic.IEnumerable`1[MB.PacketTag]'.
EdenMachine
Can you post you please post your complete code? It's a simple error.
Johannes Rudolph
sorry for the delay - I'll update with the complete code this weekend.
EdenMachine
A: 

Create a function that takes in the space delimited list of tags and returns a table. INNER JOIN your query above to the result of that function.

There are several functions written that do this. Here are two:

http://tim.mackey.ie/SQLStringSplitFunction.aspx

http://www.codeproject.com/KB/database/SQL_UDF_to_Parse_a_String.aspx

The function is also callable through linq to sql.

Raj Kaimal