challengeAccepted
challengeAccepted

Reputation: 7590

Convert int to int[]

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..

Upvotes: 2

Views: 16503

Answers (4)

Hans Olsson
Hans Olsson

Reputation: 55009

You're just getting out the one ID, I think you might have meant to loop through all the rows getting out all the IDs?

Maybe you want something like:

List<int> ids = new List<int>();
foreach(Datarow dr in ds.Tables[0].Rows)
{
    ids.Add(Convert.ToInt32(dr["Id"]));
}
int[] SampleID = ids.ToArray();

Upvotes: 4

Jon Skeet
Jon Skeet

Reputation: 1500485

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

Upvotes: 7

Lloyd
Lloyd

Reputation: 29668

That's because it's an array! Try:

int[] SampleID = new int[] {(int)dr["Id"]);

Upvotes: 1

OmerGertel
OmerGertel

Reputation: 2573

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"])};

Upvotes: 8

Related Questions