过滤逗号分隔数据

时间:2012-03-16 09:38:52

标签: linq nhibernate linq-to-nhibernate

我的网站有一堆小部件,我正在尝试根据传入的网址过滤它们。假设一个小部件具有以下结构:

public class Widget {
    public int Id { get; set; }
    public string Name { get; set; }
    public string Urls { get; set; }
}

其中Url是应显示小部件的网址的逗号分隔列表,例如:

  

/,/ Blog /,/ Blog / 123,/ News / *

新闻后的星号表示只要传入的网址以/ News /开头,就会选择小工具。

我如何根据上述条件修改以下方法来过滤小部件?

public IList<Widget> GetWidgets(string url) {
    return _session
        .Where(w => w.Urls.Contains(url))
        .ToList();
}

理想情况下,我想使用linq查询,它只能访问数据库一次。我很感激你的帮助。感谢

2 个答案:

答案 0 :(得分:1)

我设法通过添加自己的通配符匹配生成器来解决这个问题。有关如何注册生成器的示例,请参阅http://sentinel101.wordpress.com/2010/12/30/extend-nhibernate-linq-for-regex-matching/。这是任何人都感兴趣的发电机:

public class WildCardMatchGenerator : BaseHqlGeneratorForMethod {
    public WildCardMatchGenerator() {
        var methodDefinition = ReflectionHelper.GetMethodDefinition(() => WildCardMatchExtensions.WildCardMatch(null, null, ','));
        SupportedMethods = new[] { methodDefinition };
    }

    public override HqlTreeNode BuildHql(MethodInfo method, Expression targetObject, ReadOnlyCollection<Expression> arguments, HqlTreeBuilder treeBuilder, IHqlExpressionVisitor visitor) {
        return treeBuilder.Equality(treeBuilder.MethodCall("[dbo].[WildCardMatch]", new[] {
            visitor.Visit(arguments[0]).AsExpression(),
            visitor.Visit(arguments[1]).AsExpression(),
            visitor.Visit(arguments[2]).AsExpression()
        }), treeBuilder.Constant(1));
    }
}

这是WildCardMatch UDF:

CREATE FUNCTION [dbo].[WildCardMatch] (
    @Pattern NVARCHAR(MAX),
    @Input NVARCHAR(MAX),
    @Separator NVARCHAR(5)
)
RETURNS BIT
AS
BEGIN
    SET @Pattern = REPLACE(@Pattern, '*', '%')

    DECLARE @RtnValue BIT
    SELECT @RtnValue = CASE WHEN COUNT(*) > 0 THEN 1 ELSE 0 END FROM [dbo].[Split](@Pattern, @Separator) WHERE @Input LIKE [Data]

    RETURN @RtnValue
END

它调用的Split函数(来自http://blogs.microsoft.co.il/blogs/itai/archive/2009/02/01/t-sql-split-function.aspx):

CREATE FUNCTION [dbo].[Split]
(    
    @RowData NVARCHAR(MAX),
    @Separator NVARCHAR(MAX)
)
RETURNS @RtnValue TABLE 
(
    [Id] INT IDENTITY(1,1),
    [Data] NVARCHAR(MAX)
) 
AS
BEGIN 
    DECLARE @Iterator INT
    SET @Iterator = 1

    DECLARE @FoundIndex INT
    SET @FoundIndex = CHARINDEX(@Separator, @RowData)

    WHILE (@FoundIndex > 0)
    BEGIN
        INSERT INTO @RtnValue ([Data])
        SELECT Data = LTRIM(RTRIM(SUBSTRING(@RowData, 1, @FoundIndex - 1)))

        SET @RowData = SUBSTRING(@RowData, @FoundIndex + DATALENGTH(@Separator) / 2, LEN(@RowData))
        SET @Iterator = @Iterator + 1
        SET @FoundIndex = CHARINDEX(@Separator, @RowData)
    END

    INSERT INTO @RtnValue ([Data])
    SELECT Data = LTRIM(RTRIM(@RowData))

    RETURN
END

最后,您需要上述UDF的C#实现:

public static class WildCardMatchExtensions {
    public static bool WildCardMatch(this string pattern, string input, char separator = ',') {
        foreach (var str in pattern.Split(new char[] { separator }, StringSplitOptions.RemoveEmptyEntries)) {
            if (Regex.IsMatch(input, Regex.Escape(str.Trim()).Replace("\\*", ".*")))
                return true;
        }

        return false;
    }
}

希望这有帮助。

答案 1 :(得分:0)

我认为SQL服务器不允许您使用IN来表示逗号分隔的字段值。您需要LIKE(下面的SQL示例):

Urls LIKE '%_your_url_%'

Linq, Expressions, NHibernate and Like comparison可以帮助您翻译LIKE Linq到NHibernate