2016-09-08 52 views
1

我是新來的c#所以希望任何人都可以幫助我。 我有這樣的代碼,我怎麼能得到我的數組列表,而不是這個如何填充數組列表

"Length", "Color", "CHEESE", "Vesa", "none" 

ArrayList props = new ArrayList(); 
    foreach (DataRow row in dt.Rows) 
    { 
     //txt += row["Txt1"].ToString(); 
     props.Add(string.Join(",", row.ItemArray.Select(item => item.ToString()))); 
    } 

    data.AddRange(new string[] { "Length", "Color", "CHEESE", "Vesa", "none" }); 
+1

什麼是數據?你的代碼有什麼錯誤?你爲什麼使用'ArrayList'而不是泛型列表'? 。我知道你可能來自Java,但你可能需要閱讀一些C#書開始。 – user3185569

+0

你也可以用下面的代碼來替換整個循環:'List props = dt.AsEnumerable()。Select(x => String.Join(「,」,x.ItemArray.Select(i => i.ToString())) ).ToList();' – user3185569

回答

1

盡我所能從您的代碼中瞭解到,您正嘗試從dataTable中填充arraylist。你可以使用LINQ來填充你的Arraylist。 如果你真的想使用ArrayList你可以試試這個:

ArrayList props = new ArrayList(); 
props.AddRange(
       (from a in dt select new{string.Join(",", a.ItemArray.Select(item =>item.ToString()))}) 
       .ToList()); 

否則,我會建議你使用泛型列表。

1
 string[] wordsFirstExample = new string[5] { "Length", "Color", "CHEESE", "Vesa", "none" }; 

     List<string> wordsSecondExsample = new List<string>(); 
     wordsSecondExsample.Add("Length"); 
     wordsSecondExsample.Add("Color"); 

在wordsFirstExample我創建與UR所有單詞串的陣列。 in wordsSeccondExample它的所有你的單詞列表,你可以使用Add()方法逐一添加它們。