2010-09-29 19 views
17

Ho una classeCollezione di stringa utilizzando LINQ

public class Person 
{ 
    public string FirstName { get; set; } 
    public string LastName { get; set; } 
} 

List<Person> PersonList = new List<Perso>(); 
PersonList.Add(new Person() { FirstName = "aa", LastName = "AA" }); 
PersonList.Add(new Person() { FirstName = "bb", LastName = "BB" }); 

mi piacerebbe ottenere una stringa con un separatore virgola per il Cognome, utilizzando Linq, il risultato assomigliare: AA, BB

grazie,

+0

.NET 3.5 o 4.0? –

risposta

42

Se si sta utilizzando .NET 4:

string lastNames = string.Join(",", PersonList.Select(x => x.LastName)); 

Se si sta utilizzando .NET 3.5:

string lastNames = string.Join(",", PersonList.Select(x => x.LastName) 
               .ToArray()); 

(Fondamentalmente .NET 4 ha avuto alcuni sovraccarichi in più aggiunti string.Join.)

7

È possibile utilizzare

PersonList.Select(p => p.LastName).Aggregate((s1,s2) => s1 + ", " + s2); 
+0

Bella alternativa! –

8

Per concatenare oggetti stringa, con separatori, è possibile utilizzare String.Join

In .NET 3.5 e seguenti, questo accetta un array come secondo parametro, ma in 4.0 ha un sovraccarico che prende un IEnumerable<T>, dove T in questo caso è String.

Armati di questa informazione, ecco il codice che desideri.

Per .NET 3.5:

string result = String.Join(", ", 
    (from p in PersonList 
    select p.LastName).ToArray()); 

Per .NET 4.0 è possibile omettere la chiamata a ToArray:

string result = String.Join(", ", 
    from p in PersonList 
    select p.LastName); 

Se si vuole far cadere il LINQ sintassi e basta usare l'estensione LINQ metodi, qui è la stessa in tale variante:

Per NET 3,5:

string result = String.Join(", ", PersonList.Select(p => p.LastName).ToArray()); 

Per .NET 4.0 è possibile omettere la chiamata a ToArray:

string result = String.Join(", ", PersonList.Select(p => p.LastName)); 

Nota: Le varianti 3.5 di cui sopra, naturalmente, lavora a 4,0 pure, loro non rimuovere o sostituire il vecchio metodo, hanno appena aggiunto uno per il caso tipico.

Problemi correlati