Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic List.Join

Tags:

c#-4.0

I have an object

public class Title
    {
        public int Id {get; set; }
        public string Title {get; set; }
    }

How to join all Title with "-" in a List<Title> ?

like image 236
coure2011 Avatar asked Nov 26 '25 06:11

coure2011


1 Answers

I think this should give you what you're looking for. This will select the Title property from each object into a string array, and then join all elements of that array into a '-' separated string.

List<Title> lst = new List<Title>
                    { 
                        new Title{Id = 1, Title = "title1"}, 
                        new Title{Id = 2, Title = "title2"} 
                    }
String.Join("-", lst.Select(x => x.Title).ToArray());

If you're using .NET 4.0 or later, there is now an overload to String.Join that will allow you to omit the .ToArray():

String.Join("-", lst.Select(x => x.Title));
like image 160
goric Avatar answered Nov 28 '25 15:11

goric