且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在数据表复杂GROUP BY

更新时间:2023-12-01 20:01:52

我假设你的数据库查询返回CostPage和项目之间的连接。
。如果是这样的话,首先你必须将你的行以获取CostPage值,该项目到你的DTO类型之后。我真的怀疑你会看到并行代码多少好处



您的代码应该大致如下:

  costPages = table.AsEnumerable()GROUPBY(DR =方式>新的
{
CostPageNumber =博士[0]的ToString(),
说明=博士[1]的ToString(),
订单类型= Convert.ToChar(博士[2]的ToString()),
VENDORNAME =博士[3]的ToString()
})
。选择(X =>新建CostPageDTO(){
CostPageNumber = x.Key.CostPageNumber,
说明= x.Key.Description,
订单类型= X。 Key.OrderType,
VENDORNAME = x.Key.VendorName,
项= x.Select(DR = gt;新建ItemDTO {
// ItemDTO映射到这里
项ID =博士[Constants.SearchPage.ITMID]的ToString()
})了ToList()
})了ToList()。


I have a complex entity CostPageDTOas shown below:

public class CostPageDTO
{
    public string CostPageNumber { get; set; }
    public string Description { get; set; }
    public char OrderType { get; set; }
    public string VendorName { get; set; }
    public List<ItemDTO> Items { get; set; }
}

public class ItemDTO
{
    public string BrandCode { get; set; }
    public string ItemDescription { get; set; }
    public string ItemID { get; set; }
}

We need to create a List<CostPageDTO> from a datatable. I started as listed below: but I am not sure how to apply the GROUP BY clause here to create a List<ItemDTO> inside CostPageDTO.

DataTable table = new DataTable();
SqlDataReader reader = command.ExecuteReader();
table.Load(reader);
reader.Close();

List<CostPageDTO> costPages = new List<CostPageDTO>();
Parallel.ForEach(table.AsEnumerable(), (dr) =>
{
    costPages.Add(new CostPageDTO()
    {
        CostPageNumber  = dr[0].ToString(),
        Description = dr[1].ToString(),
        OrderType = Convert.ToChar(dr[2].ToString()),
        VendorName = dr[3].ToString()
    });
});

  1. How can we create the required List from DataTable

REFERENCES

  1. How do you convert a DataTable into a generic list?

I'm assuming your database query returns a join between CostPage and Item. If that's the case, first you have to group your rows to get the values for CostPage, after that project to your DTO type. I really doubt that you'll see much benefit in parallelizing the code.

Your code should look roughly like this:

costPages = table.AsEnumerable().GroupBy(dr=> new 
            {
                CostPageNumber  = dr[0].ToString(),
                Description = dr[1].ToString(),
                OrderType = Convert.ToChar(dr[2].ToString()),
                VendorName = dr[3].ToString()
            })
            .Select(x => new CostPageDTO(){
                CostPageNumber = x.Key.CostPageNumber,
                Description = x.Key.Description,
                OrderType = x.Key.OrderType,
                VendorName = x.Key.VendorName,
                Items = x.Select(dr=> new ItemDTO{
                    //ItemDTO mapping goes here
                    ItemID=dr[Constants.SearchPage.ITMID].ToString()
                }).ToList()
            }).ToList();