Linq投影,将列表展平为分层字符串



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

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

使用字符串。Join(请注意,列表需要首先在内存中),以连接Friend对象中的选定属性。如果您使用的是.NET 3.5,则需要使用ToArray()以及字符串上的重载。加入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 ) )
              };

字符串。加入是更好的方法,但滥用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)
              };

相关内容

  • 没有找到相关文章

最新更新