一起显示具有相同GUID的字段

时间:2018-09-10 06:44:24

标签: c# list entity-framework linq model-view-controller

我有一个ProductDetailDTO类型的列表。

List<ProductDetailDTO> productDTOs;

public class ProductDetailDTO
{
    public int ProductId { get; set; }
    public string Name { get; set; }
    public string Category { get; set; }
    public byte[] Image { get; set; }
    public string Description { get; set; }
    public string Brand { get; set; }
    public string GUID { get; set; }
    public string VariantName { get; set; }
    public string VariantValue { get; set; }
    public decimal Price { get; set; }
}

我已使用linq将数据绑定到列表。

var productDetails = (from product in ekartEntities.Products
                                  join productImage in ekartEntities.ProductImages on product.ProductId equals productImage.ProductId
                                  join category in ekartEntities.ProductCategories on product.Category equals category.CategoryId
                                  join mapping in ekartEntities.ProductVariantMappings on product.ProductId equals mapping.ProductId
                                  join variant in ekartEntities.ProductVariants on mapping.ProductVariantId equals variant.ProductVariantId
                                  join inventory in ekartEntities.Inventories on mapping.GUID equals inventory.Guid
                                  where product.ProductId == productDetailDTO.ProductId
                                  select new ProductDetailDTO()
                                  {
                                      ProductId = product.ProductId,
                                      Name = product.Name,
                                      Category = category.Name,
                                      Description = product.Description,
                                      Brand = product.Brand,
                                      Image = productImage.Image,
                                      GUID = mapping.GUID.ToString(),
                                      VariantName = variant.Name,
                                      VariantValue = mapping.Value,
                                      Price = inventory.Price
                                  }).ToList();

现在,我要一起显示具有相同GUID的所有变体(VariantName和VariantValue)。我该如何实现?

2 个答案:

答案 0 :(得分:1)

您可以像这样使用GroupBy和Select:

 var variants = productDTOs
                   .GroupBy(k => k.GUID)
                   .Select(v => v
                         .Select(variant => new 
                         {
                             variant.VariantName, 
                             variant.VariantValue
                         }));

答案 1 :(得分:0)

您可以使用分组依据

group p by p.GUID into g
select new { Id = g.Key, ProductDetail = g.ToList()).ToList();

如果分组之前有表格,则可以在分组本身中添加新对象

group new { p.xyz, n.xyz }
by new { p.GUID } into g

否则,请使用 let 将中间对象保存在对象中并对其进行分组