1

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 and OnlySome string array using LINQ Query ?

Thanks

2
  • 4
    Is there any particular reason you're using ArrayList instead of List<T>? Commented Mar 24, 2011 at 16:04
  • I'd also recommend you don't store your subLists as ArrayList. It seems more likely that you should be using something like: Dictionary<string,string>, List<FruitLookup>, List<KeyValuePair<string,string>> or maybe a List<Tuple<string,string>> Commented Mar 24, 2011 at 16:43

2 Answers 2

3

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();
Sign up to request clarification or add additional context in comments.

1 Comment

I'm not sure if Cast or OfType is better in cases like this. I do prefer to Cast when casting, and to use OfType when I know the collection contains elements of that type and that they are all I care about.
0

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(); 
    

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.