Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
映射值的C#字典_C#_.net_Linq - Fatal编程技术网

映射值的C#字典

映射值的C#字典,c#,.net,linq,C#,.net,Linq,我在对象报告模型中存储了一组数据,如下所示: 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 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;}
}
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();
但是,我想做的是返回一个键值对,其中包含多个属性的对象中的值,例如,汽车数量和汽车颜色列表。类似这样的事情(显然不起作用):

我尝试以不同的方式创建分组列表模型,如下所示,但不确定我是否走上了正确的道路:

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;}
}
现在我在想,这些数据作为字典的结构会更好,但我还是不确定如何从“列表”中得到我想要的结果

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; }
}
但要保持数据结构化,您可以稍微更改模型:

public class GroupedListingModel
{
    public long OwnerId { get; set; }
    public int TotalCarCount { get; set; }
    public IEnumerable<string> CarColors { get; set; }
}
    CarColors = g.Select(x => x.CarColor)