从2个可查询的结果中创建一个新的结果对象 [英] Creating a new result object from 2 iqueryable results

查看:59
本文介绍了从2个可查询的结果中创建一个新的结果对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对linq有点生疏,但这正是我想要实现的目标。

I'm a bit rusty with linq, but this is what i'm trying to achieve.

IQueryable1 =>包含嵌套产品的项目列表(产品还包含groupingId字段

IQueryable1 => List of  Items with nested Products (products also contain groupingId field

IQueryable2 =>具有分组ID的服务列表

IQueryable2 => List of Services with a grouping Id

我想返回一个新的查询结果,它几乎占用了第一个对象,并使用从query2获取的服务列表填充每个产品,并按分组ID进行过滤。

I want to return a new query result which pretty much takes the first object, and populates each product with a list of services taken from query2, filtered by the grouping id.

我想这样做而不在循环中迭代,这将触发查询执行但是想在第3个linq查询中执行它,该查询将在ToList上执行一个db调用()。

I want to do it without iterating in a loop which will trigger the queries to execute but want to do it in a 3rd linq query which will execute one db call on ToList().

类结构看起来像这样:

public class Item
{
     public int Id {get;set;}
     public string Name {get;set;}
     public List<Product> Products {get;set;}
}

public class Product
{
     public int Id {get;set;}
     public string Name {get;set;}
     public int GroupingId {get;set;}
     public List<ServiceGroup> ServiceGroup {get;set;}
}

public class ServiceGroup
{
     public int GroupingId{get;set;}
     public List<Service> Services {get;set;}
}

public class Service
{
     public int Id {get;set;}
     public string Name {get;set;}
}

感谢任何人的帮助!

 

推荐答案

嗨  Milsnips,

基于你的代码,我不确定类结构是否正确。

我认为服务类应该包含GroupingId属性作为外键。

我做了一个简单的演示基础目前的阶级结构。您可以使用以下代码参考:

IEnumerable<Item> queryable1 = db.items.Include("Products").ToList();


            IEnumerable<int> queryable2 = db.serviceGroups.Select(t=>t.GroupingId).ToList();


            var result = queryable1.Select(t => new Item()

            {

                Id = t.Id,

                Name = t.Name,

                Products = t.Products.Where(x => queryable2.Contains(x.GroupingId)).ToList()


            }).ToList();

如果您有任何问题,请随时告诉我。

最好的问候,


这篇关于从2个可查询的结果中创建一个新的结果对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆