Linq集团由多个属性组成

时间:2016-08-01 10:57:39

标签: c# linq group-by

我有一个XML文件:

<?xml version="1.0" encoding="utf-8" standalone="no"?>
<Cars>
    <Car>
        <Id>1</Id>
        <Color>Blue</Color>
        <Price>2000</Price>
    </Car>
    <Car>
        <Id>2</Id>
        <Color>Blue</Color>
        <Price>2000</Price>
    </Car>
    <Car>
        <Id>3</Id>
        <Color>Blue</Color>
        <Price>3000</Price>
    </Car>
    <Car>
        <Id>4</Id>
        <Color>Green</Color>
        <Price>2000</Price>
    </Car>
    <Car>
        <Id>5</Id>
        <Color>Green</Color>
        <Price>3000</Price>
    </Car>
</Cars>

以及相关的课程:

[XmlRoot(ElementName = "Cars")]
public class Cars        
{            
    [XmlElement(ElementName = "Car")]
    public List<Car> Car { get; set; }
}

public class Car
{
    public string Id { get; set; }

    public string Color { get; set; }

    public string Price { get; set; }
}

我想按照颜色和价格对汽车进行分组,并有一个包含组结果的列表。

我做:

Cars cars = Dezerialise<Cars>(MyXmlFile);

var group =
from c in d.Car
group c by new
{
    c.Color,
    c.Price,
} into gcs
select new Car()
{
    Color = gcs.Key.Color,
    Price = gcs.Key.Price,
};

但我有:Result

我希望在我的结果的每个索引中都有一个汽车匹配列表:group [0] =有两辆车的列表,组1 =有一辆车的列表等等

1 个答案:

答案 0 :(得分:0)

您还需要将组结果投影为:

var group =
from c in d.Car
group c by new
{
    c.Color,
    c.Price,
} into gcs
select new Cars()
{
  Car =  gcs.ToList()
};

它将为您提供如下记录:

enter image description here

使用Lambda表达式:

var group = d.Car.GroupBy(c=> new
                  {
                     c.Color,
                     c.Price
                   })
                 .Select(gcs=> new Cars()
                   {
                     Car =  gcs.ToList()
                   });