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[] { ',', ' ' });
Just use string.Join and Enumerable.Select:
string readableNames = string.Join(", ", data.Select(i => i.Name));
Easy
var str = String.Join(", ", data.Select(x => x.Name));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With