Reputation: 137
I have sets of codes in C# with array and I need to split the array into smaller size array. I have no errors when declaring the array with :
List<int> array = new List<int>();
However, the code execution prompts out error at the array.Where when I declare as :
var array = new ArrayList();
Is there any way I can use array.Where in array list? Below is my code :
List<int> array = new List<int>();
for (int i = 0; i <=20; i++){
if (unitIsPresent)
{
array.add(1);
}
else
{
array.add(0)
}
}
devidedArray = array.Where((e, i) => i >= 5 && i < 10).ToArray();
Upvotes: 2
Views: 1851
Reputation: 11808
If you really want to use an ArrayList
(really? why?), you can use OfType<int>()
to change the IEnumerable
to an IEnumerable<int>
.
var devidedArray = array.OfType<int>().Where((e, i) => i >= 5 && i < 10).ToArray();
Alternatively you could use Cast<int>()
:
var devidedArray = array.Cast<int>().Where((e, i) => i >= 5 && i < 10).ToArray();
The difference between the two is that OfType()
will silently ignore objects that cannot be cast to int
while Cast()
will fail with an InvalidCastException
.
Upvotes: 5
Reputation: 2417
https://learn.microsoft.com/en-us/dotnet/api/system.collections.arraylist?view=net-5.0
look microsoft doc.
We don't recommend that you use the ArrayList class for new development. Instead, we recommend that you use the generic List class. ...
just use List<T>
to replace ArrayList
.
Upvotes: 4
Reputation: 421
Array List is a non generic collection type so it's good to store items in array where you don't consider the items types. So for this reason you can't use Linq methods that are used for generics collections like Where. My recommendation is use a List and convert it to Array with the Linq method provided.this way is very fast.
Upvotes: 6