2016-08-02 18 views
1

Ich habe eine XML-Datei:Linq GroupBy - Wählen Sie neue Liste

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

und eine zugehörige Klasse:

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; } 
} 

ich gruppieren mag die Autos von der Farbe und Preis und hat eine Liste mit Gruppenergebnis.

ich tun:

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() 
}; 

Aber wie direkt eine neue Liste anstelle von neuen Autos wählen()?

Thx

+0

Haben Sie anonyme Liste bedeuten, die Farbe, Preis und die Liste der Autos enthält? –

+0

was ist die erforderliche Ausgabe. ein Beispiel wäre schön –

Antwort

1

Sie können nur einen anonymen Typ verwenden, ohne eine istance von Autos-Klasse zu erstellen und es sollte gut funktionieren.

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

Nach der Abfrage erhalten Sie die Autos in der Gruppe haben, die Ihnen diese foreach kann:

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