Eldo
Eldo

Reputation: 391

linq string.join

How can I get the ID along with a concatenated list of names using linq?

from m in menu
    select new
    {
       id = m.menuHeadingID, 
       items = String.Join(", ", m.menuItemName)
    }

The above query does not concatenate all menuItemName values for a single menuHeadingID.

Upvotes: 0

Views: 247

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1504162

It sounds like you actually need to group:

var menus = menu.GroupBy(m => m.MenuHeadingID)
                .Select(g => new { 
                    Id = g.Key, 
                    Items = string.Join(", ", g.Select(m => m.MenuItemName))
                 });

(I've adjusted the property names to follow .NET naming conventions.)

Upvotes: 6

Related Questions