如何跨3+列执行linq GroupBy

时间:2013-11-19 15:17:37

标签: c# linq linq-to-entities

我从以下列表开始

List items = new List();

items.add(new Vehicle { MakeID = 1, MakeName = "Oldsmobile", ModelID = 2, ModelName =   "98 Regency" });

items.add(new Vehicle { MakeID = 1, MakeName = "Oldsmobile", ModelID = 3, ModelName = "88 Delta" });

items.add(new Vehicle { MakeID = 1, MakeName = "Oldsmobile", ModelID = 4, ModelName = "Alero" });

items.add(new Vehicle { MakeID = 1, MakeName = "Oldsmobile", ModelID = 5, ModelName = "442" });

items.add(new Vehicle { MakeID = 2, MakeName = "Buick", ModelID = 11, ModelName = "Skylark" });

items.add(new Vehicle { MakeID = 2, MakeName = "Buick", ModelID = 13, ModelName = "Electra 225" });

items.add(new Vehicle { MakeID = 2, MakeName = "Buick", ModelID = 14, ModelName = "Regal" });

items.add(new Vehicle { MakeID = 2, MakeName = "Buick", ModelID = 16, ModelName = "Enclave" });

但希望它转换为以下格式:

List newList = new List();

items.add(new VehicleWithModelList { MakeID = 1, MakeName = "Oldsmobile", new List<Model> () { This list would contain the 4 oldsmobile models from above}});

items.add(new VehicleWithModelList { MakeID = 2, MakeName = "Buick", new List<Model> () { This list would contain the 4 buick models from above}});

public class Model {
    public int ModelID { get; set; }
    public string ModelName { get; set; }
}

我有以下linq到对象查询,但我不断收到语法错误,说它在最后一个右括号之前需要一个分号。

var newList = items.GroupBy(x => new {x.MakeID, x.ModelID, x.MakeName, x.ModelName}, (key, group) => new { MakeID = key.MakeID, MakeName = key.MakeName, ModelList = group.Select(z => new Model { ModelID = z.ModelID, ModelName = z.ModelName })).Cast< VehicleWithModelList >();

实现这一目标的正确方法是什么?

2 个答案:

答案 0 :(得分:1)

您在下面标记的位置错过了大括号:

var newList = items.GroupBy(x => new
    {
        x.MakeID,
        x.ModelID,
        x.MakeName,
        x.ModelName
    },
    (key, group) => new
        {
            MakeID = key.MakeID,
            MakeName = key.MakeName,
            ModelList = group.Select(z => new Model
                {
                    ModelID = z.ModelID,
                    ModelName = z.ModelName
                })
        } // <---- Here
    ).Cast<VehicleWithModelList>();

您只想通过MakeId和MakeName进行分组,否则您将为每个唯一的ModelId和ModelName获得不同的分组(它似乎不是您查询的目标:

var newList = items.GroupBy(x => new { x.MakeId, x.MakeName });

您也可以通过直接选择VehicleWithModelList对象来丢失Cast:

(key, group) => new VehicleWithModelList
    {
        MakeID = key.MakeID
        ... etc

答案 1 :(得分:1)

如下:

items.GroupBy(x => new { x.MakeID }).Select(x => new VehicleWithModelList
{
    MakeID = x.First().MakeID,
    MakeName = x.First().MakeName
    Models = x.Select(x => new Model 
    {
        ModelID = x.ModelID, 
        ModelName = x.ModelName
    }).ToList()
});

但是,如果你给我们Model的课程定义,这将有助于

看起来没有必要按MakeID和MakeName进行分组 - MakeID应该足够了,除非由于某种原因可以使用不同MakeName的MakeID。