Linq投影将列表展平为分隔的字符串

时间:2011-05-30 14:54:43

标签: linq entity projection

我正在尝试连接和逗号分隔(或空格)列表并对其进行投影。我在下面有一些示例代码。

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

    }
}

2 个答案:

答案 0 :(得分:6)

使用string.Join(注意列表需要先在内存中),以连接Friend对象中的选定属性。如果您使用的是.NET 3.5,则需要使用ToArray()以及string.Join 3.5中的重载需要一个数组。

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

答案 1 :(得分:1)

string.Join是更好的方式,但滥用LINQ真是太有趣了。

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