How to get a comma separated string from entity collection using LINQ

Waqas Anwar
26 August 2014
9782 Views

Let's say you have an entity Tutorial that contains a navigation properly called Tags and you want to display tutorial name with all the tags as a comma separated list. You can use Join method of String class to get a comma separated string from entity collection using LINQ.

var tutorialId = 10;
var query = _repository.Tutorials
  .Where(y => y.TutorialId == tutorialId)
  .ToList()
  .Select(x => new 
  { 
    Name = x.TutorialName, 
    Tags = String.Join(", ", x.Tags.Select(t => t.Name)) 
  });

The Tags will now contains all the tags of the tutorial as comma separated list as shown below: 
 HTML, CSS, JQuery