2017-10-12 41 views
0

我在C#MVC中编写标签搜索,但我只能得到所有包含其中一个单词的结果。 - 输出只应在所有输入单词匹配的位置,并且排除(例如)。 2个单词在输入中,但只有其中一个匹配。Linq SQL搜索 - 从更多匹配的标签

我迄今为止代码:

List<String> list = Request["tags"].Split(' ').ToList(); 
KDBEntities q = new KDBEntities(); 

var query = (from tag in q.KDB_tags join question in q.KDB_questions on tag.question_id equals question.id where list.Any(x => x.Equals(tag.tag)) select question); 
var Rquery = query.GroupBy(x => x.id).Select(grp => grp.FirstOrDefault()).ToList(); 


return View(Rquery); 

我一直在试图弄清楚这一点相当长一段时间,但没有运气。

希望这是有道理的,任何人都可以帮助我。

+0

您是否尝试过使用All而不是Any? – Rob

+0

是的 - 使用全部而不是任何时,如果输入多于1个单词,我没有得到任何结果。 – MadsBinger

+0

你能告诉我们更多关于KDB_questions和KDB_tags的模型吗? – Rob

回答

1

标签列表:

List<TagObj> tags = new List<TagObj>() 
{ 
    new TagObj() { Id = 1, QuestionId = 1, Tag = "news" }, 
    new TagObj() { Id = 2, QuestionId = 1, Tag = "sports" }, 
    new TagObj() { Id = 3, QuestionId = 1, Tag = "famous" }, 
    new TagObj() { Id = 4, QuestionId = 2, Tag = "news" }, 
    new TagObj() { Id = 5, QuestionId = 2, Tag = "sports" }, 
    new TagObj() { Id = 6, QuestionId = 3, Tag = "news" }, 
    new TagObj() { Id = 7, QuestionId = 4, Tag = "funny" }, 
}; 

问题清单:

List<QuestionObj> questions = new List<QuestionObj>() 
{ 
    new QuestionObj(){ QuestionId = 1, Question = "Whats up footballers?" }, 
    new QuestionObj(){ QuestionId = 2, Question = "These are famous news?" }, 
    new QuestionObj(){ QuestionId = 3, Question = "Read all about it?" }, 
    new QuestionObj(){ QuestionId = 4, Question = "You know whats funny?" } 
}; 

这些都是从请求传入标签:

var incomingTags = new List<string>() { "news", "sports" }; 

这些查询:

var query = from t in tags 
       join q in questions on t.QuestionId equals q.QuestionId 
       where incomingTags.Contains(t.Tag) 
       select new { question = q, tag = t }; 

    var result = query. 
     GroupBy(g => g.question.QuestionId). 
     Where(g => g.ToList().Select(l => l.tag.Tag).SequenceEqual(incomingTags)). 
     Select(s => s.First().question).ToList(); 
+0

执行时,我收到此错误的结果变量; System.NotSupportedException:'LINQ to Entities does not recognized the method'Boolean SequenceEqual [String](System.Collections.Generic.IEnumerable'1 [System.String],System.Collections.Generic.IEnumerable'1 [System.String]) '方法,并且此方法不能被转换为商店表达式。' – MadsBinger

+0

Aaaah是的。我认为这只是Linq2Objects方法,所以它不能很好地转换成Linq2Entites。在var result = query.ToList()的第二个查询开始.... – Rob

+0

它现在正在工作。 - 非常感谢! – MadsBinger