开发者

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 s开发者_Go百科ave 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..


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


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


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


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

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜