Click here to Skip to main content
15,888,321 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
c#
Is it possible to convert a ArrayList to a 2D int[1,13] array ?

The ArrayList is all numbers like "1111100000000", "0111110000000".
And I want them to look like this:

int[,] a = { { 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 } };


The reason I want to convert them is that I don't know how to create multi-array if conditions with an ArrayList like:

if(a[i,j] >= b[i,j])
{
do something...
}
Posted
Updated 17-Dec-15 12:13pm
v2
Comments
Sergey Alexandrovich Kryukov 17-Dec-15 16:16pm    
Yes, of course, but it depends on the content of the ArrayList and the interpretation of its data you want to use. It should be extremely simple. What's the problem?
By the way, you should not have used ArrayList in first place, as it is obsolete, System.Collections.Generic.List should be used instead. If ArrayList is legacy which you cannot change, you can use it.
—SA
Member 11380736 17-Dec-15 16:23pm    
The ArrayList is all numbers like "1111100000000", "0111110000000".
And I want them to look like this:

int[,] a = { { 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 } };


The reason I want to convert them is that I don't know how to create multi-array if conditions with an ArrayList like:

if(a[i,j] >= b[i,j])
{
do something...
}
Sergey Alexandrovich Kryukov 17-Dec-15 17:38pm    
You had to reply to my comment. I did not get any notification.
Are you saying that ArrayList elements are strings? Are they of the same length? Why so bad? Anyway, even if so, what's the problem? Why "if" conditions? (What is a an b, and so on?)
Are they numbers only 1 and 0s? If so, you would better need a BitArray on output, or array of BitArray instances, or just array[ushort]...
—SA

1 solution

You could use Linq to create an int[],[] Array:
C#
// required
using System.Linq;

int[],[] jaggedArray = aList.ToArray().Select(elem => elem.ToString().Select(ch => (int)Char.GetNumericValue(ch)).ToArray()).ToArray()

// or

int[],[] jaggedArray = aList.ToArray().Select(elem => elem.ToString().Select(ch => ch - '0').ToArray()).ToArray()

// test
int val12 = jaggedArray[1][2];;
Note: CharGetNumericValue(Char) returns a Type 'Double which means if you use it with a Unicode Char, you might get a fraction back !

I agree with Sergey that 'ArrayList is no longer a wise choice ... if it's possible ... you should use a List<List<int>>
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900