2011-03-24 44 views
1

請使用以下代碼創建一個文件夾中所有圖像的表格。vb.net - 將多個名爲XX的文件插入字符串

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
...

我想現在要做的是組中的所有這些由前兩個字符,並得到每個的總數並將它們插入單個字符串中。因此,對於上面的例子中,將是這樣的:

昏暗AA作爲字符串= 3
昏暗BB作爲字符串= 2
昏暗CC作爲字符串= 4個

任何想法如何?

回答

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 
+0

這樣的聲音可能是我正在尋找的,但我在哪裏可以將這個放在上面的例子中? – Tom 2011-03-24 15:22:04

+0

@湯姆 - 更新了我的答案 – 2011-03-24 16:02:58

+0

添加這樣的:'對於每個S在分組 的Response.Write(集團) \t \t \t RESPONSE.WRITE( 「
」) 接下來s' - 每個結果** System.Linq的。枚舉+ WhereSelectEnumerableIterator'2 [VB $ AnonymousType_0'2 [System.String,System.Collections.Generic.IEnumerable'1 [System.IO.FileInfo],VB $ AnonymousType_1'2 [System.String,System.Int32] * *那裏發生了什麼? – Tom 2011-03-24 16:54:44

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的語法,但希望這會有所幫助。

+0

我覺得子的1個參數超載指定的startIndex,而不是字符數。請參閱http://msdn.microsoft.com/en-us/library/hxthx5h6.aspx – 2011-03-24 15:14:01

+0

哎呀!修正了它 - 謝謝。 – 2011-03-24 15:24:50

相關問題