Reputation: 15475
Is there a way to take generic list and join a certain property into a comma-separated value?
public class Color
{
public int Id {get; set;}
public string Name{get; set;}
}
List<Color> list = new List<Color>();
Color c1 = new Color() { Id = 1, Name = "red" }
Color c2 = new Color() { Id = 2, Name = "blue" }
Can I do something like
list.Join(
to get
"red, blue";
Upvotes: 1
Views: 4122
Reputation: 84784
Sure, as of .NET 4 String.Join
has an overload for String.Join(string, IEnumerable<string>)
. You can even avoid calling ToString
by using the String.Join(string, IEnumerable<T>)
overload.
So these are both valid:
String.Join(",", new List<int> { 1, 2, 3 });
String.Join(",", new List<string> { "1", "2", "3" });
Upvotes: 0
Reputation: 1011
You can use String.Join for generics. But to get what you want you have to make some modifications to your code, otherwise you'll get something like this as result:
Namespace.Color, Namespace.Color
Option A as mrtig suggested:
String.Join(",", list.Select(x=>x.Name))
Option B, extend your class with ToString:
public class Color
{
public int Id {get; set;}
public string Name{get; set;}
public string ToString(){
return this.Name;
}
}
Now you can use just:
String.Join(",",list) //where list is IEnumerable<Color>
Upvotes: 0
Reputation: 2267
No, you cannot. This method is defined as string.Join(String, String[])
. There is a way to accomplish what you are trying to do:
string.Join(",", list.Select(c=>c.Name).ToArray());
Upvotes: 5
Reputation: 34234
This extension Join
stands for LINQ Join
.
List<Color> list = new List<Color>();
list.Join(...)
If you want to concatenate a collection in a string, you need to use String.Join
.
The following will result in the desired "red, blue"
string:
String.Join(", ", list.Select(x => x.Name));
Upvotes: 2