Search code examples
linqentityprojection

Linq projection that flattens a list into a deliminated string


I am trying to concat and comma deliminated (or space) a list and project it. I have some sample code below.

public class Friend
{
    public string Name { get; set; }
}

public class Person
{
    public int PersonID { get; set; }
    public string FirstName { get; set; }
    public string Surname { get; set; }
    List<Friend> Friends { get; set; }
}

public class ProjectedPerson
{
    public int PersonID { get; set; }
    public string FirstName { get; set; }
    public string Surname { get; set; }
    public string FriendsList { get; set; }
}

public class Test
{
    public void MyTest()
    {
        var query = from p in MyDataStore.Person
                select p;

       var results = from q in query
           select new ProjectedPerson
                {
                    PersonID = q.PersonID,
                    FirstName = q.FirstName,
                    Surname = q.Surname,
                    FriendsList = q.FriendsList.Concat() //??? How can I concat this and return a string           
                };

    }
}

Solution

  • string.Join is the better way but abusing LINQ is just so fun.

    var query = (from p in MyDataStore.Person
                 select p).ToList();  // <-- bring into memory with ToList()
    
    var results = from q in query
                  select new ProjectedPerson
                  {
                      PersonID = q.PersonID,
                      FirstName = q.FirstName,
                      Surname = q.Surname,
                      FriendsList = q.Friends.Aggregate<Friend, string>(null, (accum, f) => accum + (accum == null ? accum : ", ") + f.Name)
                  };