如何将Linq.IEnumerable(Of String)转换为格式化的字符串

时间:2015-02-04 11:28:28

标签: asp.net .net asp.net-4.5

我有List(Of String)存储验证错误。如果该列表包含任何项目,我想将它们连接到HTML列表中以显示每个错误。目前这很容易做到:

Dim l As List(Of String) = GetErrors()
If l.Count > 0 Then
    Dim sb As New StringBuilder
    sb.Append("<div><ul>")
    For Each s As String In l
        sb.Append(String.Format("<li>{0}</li>", s))
    Next
    sb.Append("</ul></div>")
    ltl_status.Text = sb.ToString()
End If

然而,因为这是非常冗长的,我想知道Linq是否可以提供捷径。我尝试了这个(为了清晰起见,添加了换行符):

If l.Count > 0 Then
    ltl_status.Text = String.Format("<div class=""failure""><ul>{0}</ul></div>", 
        (
        From s As String In l Select 
            String.Format("<li>{0}</li>", s)
        )
)
End If

但是,鉴于IEnumerable是一个集合,最终结果只是Literal中的这个输出:

    System.Linq.Enumerable+WhereSelectListIterator`2[System.String,System.String]

这里的目标是使用尽可能少的代码行构建列表。我看到String.Join接受一个I​​Enumerable参数,但这只是将项目连接在一起,而在这里我需要在每个项目的开头和结尾添加其他字符串。有可能吗?

答案

根据Jon Skeet的优秀建议,扩展方法为我节省了很多时间和精力:

Public Module CollectionSignatureMethods

    ''' <summary>
    ''' Takes each String value in a String collection, reformats using a format, and then returns all as a single String.
    ''' </summary>
    ''' <param name="ie">An IEnumerable(Of String) collection of string values</param>
    ''' <param name="formatString">The string format (as per String.Format)</param>
    ''' <returns>All of the Strings from the collection, reformatted and combined to a single String</returns>
    ''' <remarks>Jon Skeet is the daddy(!)</remarks>
    <Extension()> _
    Public Function JoinFormat(ie As IEnumerable(Of String), formatString As String) As String
        Return String.Join(String.Empty, ie.Select(Function(s As String) String.Format(formatString, s)))
    End Function

End Module

1 个答案:

答案 0 :(得分:2)

听起来您需要JoinSelect的组合:

String.Join("", _
  l.Select(Function(s as String) String.Format("<li>{0}</li>", s))

当然,您总是可以编写自己的JoinFormat扩展方法 - 这不会很难做到,而且可能会在所有地方都有用。例如,您可能会:

ltl_status.Text = String.Format("<div class=""failure""><ul>{0}</ul></div>",
    l.JoinFormat("<li>{0}</li>"));
相关问题