LINQ包含字符串数组中的一个匹配项 [英] LINQ contains one match from array of strings

查看:57
本文介绍了LINQ包含字符串数组中的一个匹配项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

无法使其正常工作:

    /// <summary>
    /// Retrieve search suggestions from previous searches
    /// </summary>
    public static string[] getSearchSuggestions(int SectionID, string Query)
    {
        string[] Suggestions;
        string[] Words = Query.Split(' ');

        using (MainContext db = new MainContext())
        {
            Suggestions = (from c in db.tblSearches
                        where c.SectionID == SectionID &&
                        Words.Any(w => c.Term.Contains(w))
                        select c.Term).ToArray();
        }

        return Suggestions;
    }

我得到:

System.NotSupportedException:本地序列不能在LINQ to SQL实现的查询运算符中使用,但包含运算符除外.

System.NotSupportedException: Local sequence cannot be used in LINQ to SQL implementations of query operators except the Contains operator.

我想返回记录,其中字段 c.Term 包含 Words 数组中的任何单词.我也想按比赛总数对它进行排序,但这似乎真的很难!我找到了此MSDN .但是我也无法使其与我的查询一起使用.另外,发现了这一点,但它不起作用.

I want to return records where the field c.Term contains any of the words in the Words array. I would also like to have it ordered by the total number of matches, but that seems really hard to do! I found this MSDN. But I can't get it to work with my query either. Also found this but it's not working.

推荐答案

好吧,在将其插入足够多的东西后,我意识到问题不是Any或Contains.Linq to SQL不喜欢您将本地序列(单词)与SQL集合(db.tblSearches)组合在一起.因此,为了完成此操作,您必须将其分为2个单独的查询.

Ok, after plugging away enough at it I realized that the problem wasn't the Any or the Contains. Linq to SQL doesn't like you combining the local sequence (words) with the SQL collection (db.tblSearches). So in order to accomplish this, you have to break it out into 2 separate queries.

public static string[] getSearchSuggestions(int SectionID, string Query)
{
    string[] Suggestions;
    string[] Words = Query.Split(' ');

    using (MainContext db = new MainContext())
    {
        string[] all = (from c in db.tblSearches
                    where c.SectionID == SectionID
                    select c.Term).ToArray();

        Suggestions = (from a in all
                       from w in Words
                       where a.Contains(w)
                       select a).Distinct().ToArray();


    }

    return Suggestions;
}

请记住,在第二个查询中, Contains 是区分大小写的,因此您可能必须添加不区分大小写的扩展方法,或者去老派踢一下它们 .ToUpper().我在其中一个上下文中在4.0中运行了该脚本,它正确返回了所有88个字符串(可能返回9814).虽然这是一个彻底的PITA.在这个问题上确定+1.

Keep in mind, that in the second query, the Contains is case sensitive, so you might have to add a case-insensitive extension method or go old school and kick them .ToUpper(). I ran this in 4.0 on one of my contexts and it returned all 88 strings correctly (out of a possible 9814). Though it was a thorough PITA. Definite +1 on this question.

修改:在最终答案中添加了 .Distinct().

Added .Distinct() to the final answer.

这篇关于LINQ包含字符串数组中的一个匹配项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆