1

I have these code :

var result = new Collection<object>();

result.Add(list.Select(s => new
               {
                   s.ID,
                   s.Users
               })
           );

Users is a collection which means it can contains multiple names for example "John", "Rick", "Tom", etc. I want to coalsescing it into one string "John, Rick, Tom". Any idea how to achieve this result?

Thank you

UPDATE :

Answer

var result = new Collection<object>();

result.Add(list.Select(s => new
               {
                   s.ID,
                   Users = string.Join(",", s.Users)
               })
           );
tickwave
  • 3,335
  • 6
  • 41
  • 82

2 Answers2

0

Directly from your code, it's easier to just go to

result.Add(list.Select(s => new
                {s.ID, string.Join(",",s.Users)}));

That should return you a list of pairs with ID, and joined strings of users delimited by ",".

Sava Glodic
  • 103
  • 2
  • 6
  • Already tried this and gave me error `"Invalid anonymous type member declarator. Anonymous type members must be declared with a member assignment, simple name or member access."` – tickwave Aug 24 '15 at 10:35
  • NVM I fixed it by changing `string.Join(",", s.Users)` to `Users = string.Join(",", s.Users)`. Will mark as answer in 4 mins – tickwave Aug 24 '15 at 10:37
0

If Users is a List, you can use the following code:

var result = new Collection<object>();

result.Add(list.Select(s => new
               {
                   s.ID,
                   string.Join(",", s.Users.ToArray())   
               })
           );

Also, you can check this similar question :C# List to string with delimiter

Community
  • 1
  • 1
Nikita Shrivastava
  • 2,978
  • 10
  • 20