高级搜索像LINQ

本文关键字:LINQ 搜索 高级 | 更新日期: 2023-09-27 18:18:18

我有一个内容对象列表(我在下面定义)

List<Content> ContentList;

我正在尝试创建一个使用LINQ搜索此列表的方法。方法获取列表作为参数同时也获取Query对象定义如下

public class DomainQuery
{
  public List<string> PhrasesIncludeAny { get; set; }
  public List<string> PhrasesIncludeAll { get; set; }
  public List<string> PhrasesExcludeAll { get; set; }
  public DateTime CreatedAfter { get; set; }
  public DateTime CreatedBefore { get; set; }
}
内容对象定义为
public class Content
{
  public List<string> Summary{ get; set; }
  public DateTime CreatedDate { get; set; }
}

linq语句需要遍历每个Content对象,并只选择与查询匹配的对象。短语的搜索在Summary字段中。例如,摘要必须包括PhrasesIncludeAll列表中的所有短语(蓝色,红色贪婪),任何短语:天空,土地,汽车(PhrasesIncludeAny),但不包括:加拿大,美国,英国。

高级搜索像LINQ

假设我理解你想要你的操作符做什么,它应该看起来像这样:

void Main()
{
    var queryInfo = new DomainQuery();
    var ContentList = new List<Content>();
    var query = ContentList
        .Where(q=>queryInfo.PhrasesIncludeAny
            .Any(item=>q.Summary.Any(subitem=>subitem == item)))
        .Where(q=>queryInfo.PhrasesIncludeAll
            .All(item=>q.Summary.All(subitem=>subitem == item)))
        .Where(q=>!queryInfo.PhrasesIncludeAll
            .All(item=>q.Summary.All(subitem=>subitem == item)))
        .Where(q=>q.CreatedDate < queryInfo.CreatedBefore)
        .Where(q=>q.CreatedDate > queryInfo.CreatedAfter);
}

你也可以试试这个

List<Content> ContentList = new List<Content>() 
                        { new Content { CreatedDate = DateTime.Now, Summary = new List<string>() { "America", "Pakistan", "India", "England" } }, 
                          new  Content { CreatedDate = DateTime.Now, Summary = new List<string>() { "Germany", "Holland", "Aus", "NewZealand" } }};
DomainQuery domainQuery = new DomainQuery { CreatedAfter = DateTime.Now.AddDays(-4), PhrasesExcludeAll = new List<string>() { "Aus" }, CreatedBefore = DateTime.Now, PhrasesIncludeAll = new List<string>() { "America", "Pakistan", "India", "England" }, PhrasesIncludeAny = new List<string>() { "India" } };
var result = ContentList.Where(c => domainQuery.PhrasesIncludeAny
                        .Any(item => c.Summary.Any(subItem => subItem == item))
           && !domainQuery.PhrasesExcludeAll.Any(item => c.Summary.Any(subItem => subItem == item))
           && !c.Summary.Except(domainQuery.PhrasesIncludeAll).Any()
           && c.CreatedDate < domainQuery.CreatedBefore
           && c.CreatedDate > domainQuery.CreatedAfter);

        foreach (var res in result)
        {
            res.Summary.ForEach(r => {
                    Console.WriteLine(r);
                });
        }
        Console.ReadKey();