user6313890
user6313890

Reputation:

Linq GroupBy - Select new list

I have a XML file :

<?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>
</Cars>

And an associated class :

public class Cars
{
    public List<Car> Car { get; set; }
}

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

    public string Color { get; set; }

    public string Price { get; set; }
}

I want to group the cars by the Color and Price and have a List with group result.

I do :

Cars cars = Dezerialise<Cars>(MyXmlFile);

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

But how to select directly a new List instead of new Cars() ?

Thx

Upvotes: 1

Views: 736

Answers (1)

Kerim Emurla
Kerim Emurla

Reputation: 1151

You can just use an anonymous type without creating an istance of Cars class and it should work just fine.

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

After the query you will have the cars in group, which you can foreach like this:

foreach (var group in groups)
        {
            foreach (var car in group.Cars)
            {
                Console.WriteLine(car.Color);
            }
        }

Upvotes: 1

Related Questions