23

I have a class

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

I'd like get a string with a comma separator for the LastName, using Linq, the result look like: AA,BB

Thanks,

TheBoubou
  • 19,487
  • 54
  • 148
  • 236

3 Answers3

59

If you're using .NET 4:

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

If you're using .NET 3.5:

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

(Basically .NET 4 had some extra overloads added to string.Join.)

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
10

You can use

PersonList.Select(p => p.LastName).Aggregate((s1,s2) => s1 + ", " + s2);
Jens
  • 25,229
  • 9
  • 75
  • 117
8

To concatenate string items, with separators, you can use String.Join

In .NET 3.5 and below, this takes an array as the second parameter, but in 4.0 it has an overload that takes an IEnumerable<T>, where T in this case is String.

Armed with this information, here's the code you want.

For .NET 3.5:

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

For .NET 4.0 you can omit the call to ToArray:

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

If you want to drop the LINQ-syntax and just use the LINQ extension methods, here's the same in that variant:

For .NET 3.5:

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

For .NET 4.0 you can omit the call to ToArray:

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

Note: The 3.5 variants above of course works in 4.0 as well, they did not remove or replace the old method, they just added one for the typical case.

Lasse V. Karlsen
  • 380,855
  • 102
  • 628
  • 825