Reputation: 473
public class Item
{
public string id { get; set;}
public string Color { get; set;}
}
public class Test
{
public ICollection<Item> Items { get; set; }
public void ConCat
{
string a = ?
}
}
I have above class structure and i want to concatenate colors in all the item within that collocation using LINQ. Any idea how to do this?.
Upvotes: 3
Views: 5523
Reputation: 8271
Try this:
var res = yourList.Select(x => x.Name).Aggregate((current, next) => current + ", " + next);
But, I recommend you to use String.Join(string separator, IEnumerable<string> values)
:
var res = String.Join(";", yourList.Select(x => x.Name));
Additional Information:
In such situations you can use either Aggregate
or String.Join()
. If we tests the execution times of the both query, we will see that the second is faster than the first one. But the reason is not Aggregate()
function. The problem is we are concatenating strings in a loop. It will cause a lots of intermediate strings which will cause a bad performance. You can use StringBuilder.Append
, if you want still to use Aggregate and increase the performance:
var res = yourList.Select(x => x.Name)
.Aggregate(new StringBuilder(), (current, next) => current.Append(next).Append(", "))
But, String.Join()
uses a StringBuilder
internally already and for that reason it will be the best choice
Upvotes: 2
Reputation: 10068
You can return a comma-separated string of all colors. Use String.Join
to concatenate strings with ,
separator as shown below.
public class Item
{
public string id { get; set;}
public string Color { get; set;}
}
public class Test
{
public ICollection<Item> Items { get; set; }
public string AllColors()
{
return string.Join(",", Items.Select(i => i.Color));
}
}
Upvotes: 0
Reputation: 48972
Try:
string a = string.Join(";", Items.Select(item => item.Color));
Upvotes: 3