Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert int to int[]

Tags:

c#

asp.net

I have a dataset and i am trying to get all the Ids of the datset into a datarow to finally save it in a int array. Its not working for me. It says "Cannot implicitly convert from type int to int[]"

Dataset ds = new BusinessLogic().Getsamples(MerchantID);

Datarow dr = ds.Tables[0].Rows[0];

int[] SampleID = Convert.ToInt32(dr["Id"]);

Thanks in advance..

like image 400
challengeAccepted Avatar asked Dec 02 '25 08:12

challengeAccepted


2 Answers

You have to create a new int array and put the int in there.

int sampleID = new int[1];
sampleID[0] = Convert.ToInt32(dr["Id"]);

I think this shorthand will work too:

int[] SampleID = new int[]{Convert.ToInt32(dr["Id"])};
like image 175
OmerGertel Avatar answered Dec 04 '25 00:12

OmerGertel


Well yes. Look at this line:

int[] SampleID = Convert.ToInt32(dr["Id"]);

The right hand side is an int (the result of Convert.ToInt32) but you're trying to convert that into an array.

If you want all the IDs, I suggest you create a List<int> and iterate over the rows, calling list.Add(Convert.ToInt32(dr["Id"]) for each row and then call ToArray() at the end if you really need to.

Alternatively, use LINQ - something like:

int[] ids = ds.Tables[0].AsEnumerable()
                        .Select(dr => dr.Field<int>("Id"))
                        .ToArray();
like image 28
Jon Skeet Avatar answered Dec 03 '25 23:12

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!