Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenating list item properties

Tags:

c#

generics

I'm looking for an elegant way of creating a readable form some property of all items living in a Generic.List.

Let me illustrate it by an example. I have a data structure like this:

public class InfoItem {
    public string Name { get; set; }
    public string Description { get; set; }
}

Here is how I would use it in my code:

List<InfoItem> data = new List<InfoItem>();
data.Add(new InfoItem() { Name = "Germany", Description = "Describes something" });
data.Add(new InfoItem() { Name = "Japan", Description = "Describes something else" });
data.Add(new InfoItem() { Name = "Austria", Description = "And yet something else" });

Now, what I want to get, is a string like "Germany, Japan, Austria". Is there some LINQ or generics magic that would do it better than this primitive loop?

string readableNames = "";
foreach (var item in data) {
    readableNames += item.Name + ", ";
}
readableNames = readableNames.TrimEnd(new char[] { ',', ' ' });
like image 716
naivists Avatar asked Dec 05 '25 14:12

naivists


2 Answers

Just use string.Join and Enumerable.Select:

string readableNames = string.Join(", ", data.Select(i => i.Name));
like image 76
Zbigniew Avatar answered Dec 08 '25 02:12

Zbigniew


Easy

var str = String.Join(", ", data.Select(x => x.Name));
like image 45
I4V Avatar answered Dec 08 '25 02:12

I4V



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!