Concat查询结果并将不同结果合并到列表中

时间:2019-03-15 01:46:00

标签: c# entity-framework linq .net-core

假设以下表格:

tblColor:

id - name  
1 - red  
2 - blue  
3 - green 

tblProducts

id -  name  
1 - TV   
2 -  radio

tblProductColors

id - productId - colorId  
1 - 1 - 1  
2 - 1 - 2  
3 - 2 - 2  
4 - 2 - 3

然后我可以通过EF Linq来查询:

name - color  
tv - red  
tv -  blue  
radio - blue  
radio - green

但是我需要得到:
电视红色,蓝色
无线电蓝色,绿色

我认为在查询后循环并列出列表不是一个好主意
我也认为该解决方案必须具有快速的性能
我的主要问题是结果的速度

谢谢

1 个答案:

答案 0 :(得分:1)

Linq的GroupBy将是您想要的。

首先,要获取具有相关颜色的产品列表...

var results = context.ProductColors
    .Select(x => new {ProductName = x.Product.Name, ColorName = x.Color.Name})
    .GroupBy(x => x.ProductName)
    .ToList() // Needed for the string.Join since EF won't understand that.
    .Select( group => new 
    {
        ProductName = group.Key, // Product.Name
        Colours = string.Join(", ", group.Select(x=> x.ColourName)); // Colour.Names
    }).ToList();

编辑:为避免多余的ToList,请将结果选择到ViewModel中,并让ViewModel设置颜色格式:

public class ProductColourSummary
{
   public string ProductName { get; set; }
   public List<string> Colors { get; set; } = new List<string>();

   public string FlattenedColors
   {
       get { return string.Join(", ", Colors); }
   }
}
var results = context.ProductColors
    .Select(x => new {ProductName = x.Product.Name, ColorName = x.Color.Name})
    .GroupBy(x => x.ProductName)
    .Select( group => new ProductColorSummary
    {
        ProductName = group.Key, // Product.Name
        Colours = group.Select(x=> x.ColourName).ToList()
    }).ToList();

然后使用result.ProductName和result.FlattenedColors显示结果。

相关问题