Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Collection to string using linq

Tags:

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,

like image 512
Kris-I Avatar asked Sep 29 '10 11:09

Kris-I


People also ask

How to convert collection into string in c#?

parameters = string. Join("", requestParameters. Select(x => string. Concat(x.

Can you use Linq on strings?

LINQ can be used to query and transform strings and collections of strings. It can be especially useful with semi-structured data in text files. LINQ queries can be combined with traditional string functions and regular expressions. For example, you can use the String.

How do you concatenate in Linq?

In LINQ, the concatenation operation contains only one operator that is known as Concat. It is used to append two same types of sequences or collections and return a new sequence or collection. It does not support query syntax in C# and VB.NET languages. It support method syntax in both C# and VB.NET languages.


2 Answers

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.)

like image 92
Jon Skeet Avatar answered Oct 20 '22 03:10

Jon Skeet


You can use

PersonList.Select(p => p.LastName).Aggregate((s1,s2) => s1 + ", " + s2); 
like image 37
Jens Avatar answered Oct 20 '22 03:10

Jens