使用LINQ如何在集合中连接itesm的字符串属性

leo*_*ora 7 c# linq

我有一个集合中的对象列表.每个对象都有一个名为Issue的字符串属性.我想连接集合中所有项目的问题,并将它们放入一个字符串中.使用LINQ这是最干净的方法是什么.

这是手动方式:

 string issueList = "";
 foreach (var item in collection)
 {
       if (!String.IsNullOrEmpty(item.Issue)
       {
             issueList = issueList + item.Issue + ", ";
       }
 }
 //Remove the last comma
 issueList = issueList.Remove(issueList.Length - 2);
 return issueList;
Run Code Online (Sandbox Code Playgroud)

SLa*_*aks 21

你可以写

return String.Join(", ", collection.Select(o => o.Issue));
Run Code Online (Sandbox Code Playgroud)

在.Net 3.5中,您需要添加.ToArray().