开发者

Linq projection that flattens a list into a deliminated string

开发者 https://www.devze.com 2023-03-09 13:13 出处:网络
I am trying to concat and comma deliminated (or space) a list and project it. I have some sample code below.

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; }
  开发者_JAVA百科  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           
                };

    }
}


Use string.Join (note that the list will need to be in memory first), to concatentate the selected properties from your Friend objects. If you are using .NET 3.5, you'll need to use ToArray() as well as the overloads on string.Join in 3.5 require an array.

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 = string.Join( ", ", q.Friends.Select( f => f.Name ) )
              };


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)
              };
0

精彩评论

暂无评论...
验证码 换一张
取 消