vb.net - 将名为XX的文件数插入到字符串中

时间:2011-03-24 15:00:41

标签: asp.net vb.net server.mappath

使用以下代码创建文件夹中所有图像的表格。

VB:

Sub Page_Load(sender as Object, e as EventArgs)
    If Not Page.IsPostBack then
      Dim dirInfo as New DirectoryInfo(Server.MapPath("/images"))
      articleList.DataSource = dirInfo.GetFiles("*.jpg")
      articleList.DataBind()
    End If
  End Sub

体:

<asp:DataGrid runat="server" id="articleList" AutoGenerateColumns="False" ShowHeader="false">
    <Columns>
      <asp:BoundColumn DataField="Name" />
    </Columns>
  </asp:DataGrid>

结果看起来像这样:

aa_01.jpg
aa_02.jpg
aa_03.jpg
bb_01.jpg
bb_02.jpg
cc_01.jpg
cc_02.jpg
cc_03.jpg
cc_04.jpg
...

我现在要做的是将前两个字符分组,并获取每个字符的总数,并将它们插入单个字符串中。因此,对于上面的示例,它将类似于:

Dim aa As String = 3
Dim bb As String = 2
Dim cc As String = 4

任何想法如何?

2 个答案:

答案 0 :(得分:1)

你可以使用Linq来做到这一点。试试这个。

dim q = From p in articles _
        Group By Name = p.Name.SubString(0,2) into g = group _
        Select GroupName = Name, _
               Count = g.Count()

更新(根据评论提供一些上下文)

Sub Page_Load(sender as Object, e as EventArgs)

    If Not Page.IsPostBack then
      Dim dirInfo as New DirectoryInfo(Server.MapPath("/images"))
      Dim articles = dirInfo.GetFiles("*.jpg")

      articleList.DataSource = articles
      articleList.DataBind()

      Dim groupings = From p in articles _
                      Group By Name = p.Name.SubString(0,2) into g = group _
                      Select GroupName = Name, _
                             Count = g.Count()

      ' do whatever you like with the groupings '
    End If

End Sub

答案 1 :(得分:0)

在C#中,使用LINQ:

groupedArticleList = (from a in articleList
                      group a by a.Name.Substring(0, 2) into g
                      select new
                      {
                          GroupName = g.Key,
                          ArticleCount = g.Count()
                      });

您无法将它们真正提取到单独的变量中,但您可以按原样使用groupedArticleList并循环播放它或将其转换为Dictionary<string, int>

抱歉,我不知道VB的语法,但希望这会有所帮助。