使用linq在多个级别上搜索多个列表

时间:2013-11-06 20:35:57

标签: c# .net linq entity-framework

这将是快速和肮脏的,但应该给你的想法。我以前做过,但找不到我做的地方,也不记得因为它已经这么久了。我需要搜索多个级别的列表....

示例:搜索“猪”

var query = context.Farms.OrderBy(x => x.FarmName).Select(f => new FarmItem
{
    FarmId = f.FarmId,
    FarmName = f.FarmName,                    
    Fields = f.Fields.OrderBy(x => x.FieldName).Select(d => new FieldItem
    {
        FieldId = d.FieldId,
        FieldName = d.FieldName,
        Animals = d.Animals.OrderBy(x => x.AnimalName).Select(a => new AnimalItem
        {
            AnimalId = a.AnimalId,
            AnimalName = a.AnimalName
        })
    })
});

我需要查看“pig”是否在FarmName,FieldName或AnimalName和

  1. 如果在名称中找到“pig”,并返回所有字段,并且它是字段中的动物,则返回农场
  2. 返回带有“pig”字段的字段以及它的农场和所有野外动物
  3. 以“猪”的名义及其字段返回计划,并且它是田地的农场

1 个答案:

答案 0 :(得分:0)

这应该有效(未经测试):

var query = context.Farms.OrderBy(x => x.FarmName).Select(f => new FarmItem
{
    FarmId = f.FarmId,
    FarmName = f.FarmName,                    
    Fields = f.Fields.OrderBy(x => x.FieldName).Select(d => new FieldItem
    {
        FieldId = d.FieldId,
        FieldName = d.FieldName,
        Animals = d.Animals.OrderBy(x => x.AnimalName).Select(a => new AnimalItem
        {
            AnimalId = a.AnimalId,
            AnimalName = a.AnimalName
        }).Where(a => a.AnimalName.Contains("pig"))
    }).Where(d => d.FieldName.Contains("pig") || d.Animals.Any())
}).Where(d => f.FarmName.Contains("pig") || f.Fields.Any());