2016-08-01 10 views
0

ich eine XML-Datei haben:Linq-Gruppe durch eine mehrere Eigenschaften

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

und eine zugehörige Klasse:

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

ich gruppieren möchten die Autos von der Farbe und Preis und haben 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 Car() 
{ 
    Color = gcs.Key.Color, 
    Price = gcs.Key.Price, 
}; 

Aber ich habe: Result

ich in jedem Index meines Ergebnis wollen eine Liste der Auto-Matching: Gruppe [0] = Liste mit zwei Autos, Gruppe 1 = Liste mit einem Auto etc etc

Antwort

0

Sie müssen auch das Konzernergebnis projizieren wie:

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

Es wird Ihnen Aufzeichnungen geben wie:

enter image description here

Mit Lambda Expression:

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

Sie wieder Select für das –

+0

mit Projekt tun haben bedeutet, dass Sie einzelne '' Liste ''? wenn das der Fall ist, warum Sie aufsuchen? –

+0

wie: '' var Carrs = group.SelectMany (x => x.Car); '' –