【问题标题】:What is the best way to check if list contain any element of specific collection?检查列表是否包含特定集合的任何元素的最佳方法是什么?
【发布时间】:2021-02-18 00:43:35
【问题描述】:

获取仅包含一些数据的列表的最佳方法是什么?

我的应用程序在 ASP.NET CORE 5 Web API 上。它有KitchenOrigins,每个都包含Recipes的集合。

   public class KitchenOrigin
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public string Code { get; set; }
            public ICollection<Recipe> Recipes { get; set; }
        }
    }

当我的应用程序运行时,我正在播种一些数据 (Recipes)。

KitchenOrigins 非常多,所以我只想获取包含Recipes 的KitchenOrigins 列表。

就像标题一样:最好的方法是什么? 也许IQueryable?你能帮我解决这个问题吗?

这是我的代码:

回购

 public async Task<IEnumerable<KitchenOrigin>> GetKitchenOriginsWithRecipesAsync()
        {
            return await _context.KitchenOrigins
            .Include(k => k.Recipes)
           .ToListAsync();
        }

控制器

[HttpGet("kitchen-origins")]
        public async Task<ActionResult> GetKitchenOrigins()
        {
            var kitchenOrigins = await _recipeRepository.GetKitchenOriginsWithRecipesAsync();
            return Ok(kitchenOrigins);
        }

【问题讨论】:

    标签: c# asp.net-core entity-framework-core asp.net-core-webapi asp.net-core-5.0


    【解决方案1】:

    您可以使用.Where()进行过滤,使用.Any()检查是否为空。

    public async Task<IEnumerable<KitchenOrigin>> GetKitchenOriginsWithRecipesAsync()
    {
        return await _context.KitchenOrigins
          .Where(k => k.Recipes.Any())
          .Include(k => k.Recipes)
          .ToListAsync();
    }
    

    【讨论】:

    • 打败了我,但是你能把谓词和条件放在 op 的 any 语句中吗
    • @SimonPrice 我相信他只是想要具有食谱的 kitchenOrigins 并没有为食谱指定任何过滤/谓词。除非我错过了什么
    猜你喜欢
    • 2016-07-02
    • 2017-06-05
    • 2014-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-09
    • 1970-01-01
    相关资源
    最近更新 更多