C#在一个大型LINQ查询中对一个源进行几个LINQ查询 [英] C# several LINQ queries in one big LINQ query to the one source

查看:58
本文介绍了C#在一个大型LINQ查询中对一个源进行几个LINQ查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请帮我进行c#编码,因为我几年来都没有使用c#进行编码.我有包含此数据的数据表:

Please, help me with c# coding since I hven't been coding in c# for couple of years. I have datatable which contains this data:

数据表的内容

我还有下一节课:

public class Warehouse
{
   public int warehouseId;
   public Product[] products;
}
public class Product
{
  public int productId;
  public ProductOrigin[] productOrigins
}
public class ProductOrigin
{
  public int productOriginId;
  public Supplyer[] supplyers;
}
public class Supplyer
{
  public int supplyerId;
  public decimal volume
}

(根据xsd方案生成类).我必须在datatable Warehouse []仓库变量中填充数据.现在我做了很多嵌套的 foreach 循环,对相同的数据进行了多次查询.因此,首先我要对LINQ进行分组查询以获取唯一的仓库,然后先进行foreach,然后再进行LINQ查询以从同一数据表中的一个仓库中获取唯一的productId,然后嵌套foreach,然后再进行另一个查询并嵌套foreach,然后再进行下一个查询(总共4或5层)).该代码非常庞大,看起来非常糟糕.我记得有一种方法可以在一个Linq查询中收集所有需要的信息,以仅使用嵌套的foreach循环,而无需在每个foreach中重新查询来自同一源的数据,但是不要忘记在哪里看到它.您能提醒我一下,我该怎么做(或者还有另一种方式)?

(classes were generated according to xsd scheme). I have to fill with data in datatable Warehouse[] warehouses variable. Now I do lots of nested foreach cycles with several queries to the same data. So first i do LINQ query with grouping to get unique warehouses then first foreach then LINQ query to get unique productIds in one warehouse from the same datatable then nested foreach, then another query and nested foreach then the next one (4 or 5 layers in total). The code is huge and looks very aweful. I remember there was a way to gather all needed information in one Linq query to use nested foreach cycles only without requerying data from the same source in every foreach, but don't remeber where I saw it. Could you remind me, please, how can I do that (or maybe there is another way)?

推荐答案

我假设您需要以下查询:

I assume you need the following query:

var warehouses =
    context.Wharehouse
    .AsEnumerable()
    .GroupBy(w => w.warehouseId)
    .Select(gw => new Warehouse
    {
        warehouseId = gw.Key,
        products = gw
            .GroupBy(p => p.productId)
            .Select(gp => new Product 
            {
                productId = gp.Key,
                productOrigins = gp
                    .GroupBy(po => po.productOriginId)
                    .Select(gpo => new ProductOrigin
                    {
                        productOriginId = gpo.Key,
                        supplyers = gpo
                            .Select(s => new Supplyer
                            {
                                supplyerId = s.supplyerId,
                                volume = s.Amount
                            })
                            .ToArray()
                    })
                    .ToArray()
            })
            .ToArray()
    })
    .ToArray();

这篇关于C#在一个大型LINQ查询中对一个源进行几个LINQ查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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