我有点迷路了,我尝试了几种不同的方法来解决它。到目前为止,我很难写出LINQ来做我想做的事情。LINQ多个关键字搜索PagedList
我想采用用户输入字符串,可以是多个关键字,可以用空格或“,”分隔。
这里的工作是抓住整个搜索词,并将其与Post或任何标签中的标题进行比较。我希望用户输入“HTML预览”,它将匹配一个名为“预览世界”的帖子,标记为“HTML”,“CSS”等。
此查询不起作用。 ..但我试图修改它,以便它工作。
public IPagedList<Post> SearchResultList(string searchTerm, int resultsPerPage, int page)
{
string[] terms = searchTerm.Split(null);
TNDbContext context = DataContext;
return context.Posts
.Include(a => a.Tags)
.Include(b => b.Comments)
.Where(c => (c.Title.Contains(searchTerm) || c.Tags.Any(d => d.Name.StartsWith(searchTerm))) || searchTerm == null)
.OrderByDescending(x => x.Views)
.ToPagedList(page, resultsPerPage);
}
我试着写的,而不是其他的 “去哪儿” 的语句
.Where(x => (terms.All(y => x.Title.Contains(y))) || terms == null)
这一点,但它不断抛出这个错误
无法比拟 'System.String []' 类型的元素。只支持原始类型,枚举类型和实体类型。
供参考:
public class Post
{
public Post()
{
Tags = new HashSet<Tag>();
Comments = new HashSet<Comment>();
}
public int Id { get; set; }
public string Title { get; set; }
public string UrlTitle { get; set; }
public DateTime Date { get; set; }
public DateTime DateEdited { get; set; }
public string Body { get; set; }
public string Preview { get; set; }
public string PhotoPath { get; set; }
public int Views { get; set; }
//Navigational
public ICollection<Tag> Tags { get; set; }
public ICollection<Comment> Comments { get; set; }
}
public class Tag
{
public Tag()
{
Post = new HashSet<Post>();
}
public int Id { get; set; }
public string Name { get; set; }
public int TimesTagWasUsed { get; set; }
//Navigational
public ICollection<Post> Post { get; set; }
}
我修改这个稍微因为我可能是一点点不清楚。我想用空格或逗号分隔搜索词。无论是所有的善良的人,我都非常感谢这个人的大脑放屁。 我只是把它留给只用空白符分割,如下所示: string [] terms = searchTerm.Split(null); – Spets 2015-02-11 04:22:13