开发者

vb.net - Inserting number of files named XX into a string

Have the following code which creates a table of all the images in a folder.

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

Body:

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

The results look something like this:

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

...

What I want to do now is group all these by the first two characters and get the total number for each and insert them into individual strings. So for the above example it 开发者_如何学编程would be something like:

Dim aa As String = 3

Dim bb As String = 2

Dim cc As String = 4

Any ideas how?


You can do this using Linq. Try this.

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

Update (to give a bit of context as per comments)

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


In C#, using LINQ:

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

You can't really extract them into separate variables but you could use groupedArticleList as-is and loop through it or convert it to a Dictionary<string, int>.

Sorry I don't know the VB syntax but hopefully that will help.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜