我有一个Content对象列表(我在下面定义)
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对象,并只选择与查询匹配的对象。短语的搜索位于“摘要”字段中。例如,摘要必须包括PhrasesIncludeAll列表中的所有短语(蓝色,红色贪婪),任何短语:sky,land,car(PhrasesIncludeAny),但不包括:Canada,US,UK。
答案 0 :(得分:1)
假设我理解你想让你的操作员做什么,应该看起来像这样:
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);
}
答案 1 :(得分:0)
你也可以试试这个
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();