Array of string from Arraylist of Arraylist
I want to create an array of string from Arraylist of Arraylist.
Here is a code:
ArrayList MainList = new ArrayList();
ArrayList subList = new ArrayList();
subList.Add("A");
subList.Add("Apple");
MainList.Add(subList);
subList = new ArrayList();
subList.Add("B");
subList.Add("Banana");
MainList.Add(subList);
subList = new ArrayList();
subList.Add("C");
subList.Add("Caret");
MainList.Add(subList);
string[] AllList = { "A", "Apple", "B", "Banana", "C", "Caret" };
string[] OnlySome = { "Apple", "Banana", "Caret" };
I know we can do it using for each loop but how can I get AllList 开发者_如何学Pythonand OnlySome string array using LINQ Query ?
Thanks
Sure:
var allList =
MainList.
Cast<ArrayList>().
SelectMany(a => a.Cast<string>()).
ToArray();
var onlySome =
MainList.
Cast<ArrayList>().
Select(a =>
a.Cast<string>().
Skip(1).
First()).
ToArray();
I wasn't sure what was the exact condition for OnlySome, therefore I thought 2 options,
- Select every other element (odd indexed, even location)
onlySome1
Select any string which has a length greater than 1
onlySome2
var allList = (from al in MainList.ToArray() from s in (al as ArrayList).ToArray() select s as string).ToArray(); // if you want to select every other element var onlySome1 = allList.Where((s, index) => index % 2 == 1).ToArray(); // if you want to select all the strings with 2 or more characters. var onlySome2 = allList.Where(s => (s as string).Length > 1).ToArray();
精彩评论