coure2011
coure2011

Reputation: 42474

Generic List.Join

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

Upvotes: 3

Views: 10766

Answers (2)

goric
goric

Reputation: 11905

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

Upvotes: 11

Jake Kalstad
Jake Kalstad

Reputation: 2065

list.Select(x => x.Title).Aggregate((current, next) => current + "-" + next);

should return a string of them all chained by a -

Upvotes: 2

Related Questions