0

I'm trying to be concise. I couldn't find answers online, though I'm sure they're there, but I reviewed these questions on SO and didn't find what I was looking for:

compare-and-retrieve-elements-from-arraylist

getting-index-of-an-item-in-an-arraylist

getting-a-particular-arraylist-element

I have an ArrayList with a number of arrays in them, each of which are one-dimensional and have varying amounts of elements (both string and int). How can I access the elements in the ArrayList?

3
  • Please remove the arraylist tag if it doesn't apply. While C# does have a class under System.Collections called ArrayList, the tag explicitly cites Java, so I'm not sure if I should use it. Commented Feb 18, 2014 at 23:50
  • What type of elements do you want to access ? all elements inside of one-dimensional arrays ? Commented Feb 18, 2014 at 23:51
  • The ArrayList contains lists of arrays. Those arrays have varying numbers of items in them. The items in any of those arrays can be either strings or integers, and may appear in different configurations. Commented Apr 6, 2014 at 1:54

2 Answers 2

0

You can use OfType and SelectMany,for example you can get all string and integer values inside of one-dimensional arrays like this:

ArrayList arr = new ArrayList();
arr.Add(new []{ 1, 2, 3, 4, 5});
arr.Add(new [] {"asdas", "asdsa"});
var stringValues = arr.OfType<Array>()
                      .SelectMany(x => x.OfType<string>());  // asdas asdsa
var intValues = arr.OfType<Array>()
                   .SelectMany(x => x.OfType<string>());  // 1 2 3 4 5
Sign up to request clarification or add additional context in comments.

9 Comments

I can't find the methods OfType or SelectMany. I am not familiar with Linq, but it looks like (according to the answer below) that might be what you are talking about.
@Stopforgettingmyaccounts... what version of .NET Framework you are using? add a reference to System.Linq.dll, using System.Linq
The using statement works and I am using version 4.0. I didn't know any references added methods to other references. The Linq import added OfType(), but it did not add SelectMany().
it is not possible, SelectMany is supported in 4.0 see documentation, and also SelectMany and OfType are in the same assembly.You are doing something wrong.
@Stopforgettingmyaccounts... SelectMany method doesn't take ArrayList as first parameter.You should use OfType or Cast methods to access that method because it takes IEnumerable<T>.See my answer, did I use Arraylist.SelectMany ?
|
0

Linq has an extension method SelectMany that will make it look like all the child lists are one list

array.SelectMany( i => i );

Comments

Your Answer

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