来自映射值的C#字典

时间:2016-07-20 15:20:48

标签: c# .net linq

我有一组数据存储在对象ReportModel中,如下所示:

public class ReportModel
{
   public List<CarListingModel> CarListings {get; set;}
}

public class CarListingModel
{
   public long CarId {get; set;}
   public long OwnerId {get; set;}
   public string CarColor {get; set;}
}

public class GroupedListingModel
{
   public long OwnerId {get; set;}
   public int TotalCarCount {get; set;}
   public string CarColors {get; set;}
}

我已经在CarListingModel对象中选择了一组数据,如下所示:

var list = someData.Where(...).Select(l => new CarListingModel 
{
       CarId = l.CarId,
       OwnerId = l.OwnerId,
       CarColor = l.Color
});

我用来获取与每个OwnerId对应的TotalCarCount的代码如下所示:

var result = list.GroupBy(p=> p.OwnerId, p=> p.CarId, (key, g) => new GroupedListingModel  {
   OwnerId = key,
   TotalCarCount = g.Count()
}).ToList();

但是,我想要做的是返回一个键值对,其中包含多个属性的对象中的值,例如,汽车数量和汽车颜色列表。像这样的东西(显然不起作用):

var result = list.GroupBy(p=> p.OwnerId, p=> p.CarId, p=> p.CarColor (key, g1, g2) => new GroupedListingModel  
{  OwnerId = key,
   TotalCarCount = g1.Count(),
   CarColors = string.Join(", ", g2.ToList());
}).ToList();

我试图以不同的方式创建分组列表模型,但不确定我是否在正确的道路上:

public class GroupedListingModel_2
{
   public long OwnerId {get; set;}
   public DetailsModel Details {get; set;}
}

public class DetailsModel
{
   public int TotalCarCount {get; set;}
   public string CarColors {get; set;}
}

现在我认为这些数据会更好地构建为字典,但我再次不确定如何从“#list”列表中获取数据。达到我想要的结果。

1 个答案:

答案 0 :(得分:2)

var result = list.GroupBy(p => p.OwnerId, (key, g) => new GroupedListingModel
{
    OwnerId = key,
    TotalCarCount = g.Count(),
    CarColors = string.Join(", ", g.Select(x => x.CarColor).Distinct().OrderBy(x => x)),
}).ToList()

但是为了保持数据结构,你可以稍微改变你的模型:

public class GroupedListingModel
{
    public long OwnerId { get; set; }
    public int TotalCarCount { get; set; }
    public IEnumerable<string> CarColors { get; set; }
}

GroupBy结果选择器:

    CarColors = g.Select(x => x.CarColor)