Question

I have a DataTable which is having a hundred of rows, and many columns. One of the column is - "ImageThumbnail" I want to display the thumbnail in one control on form. This control expects an "ImageList" as its image source. So I like my ImageList control to get populated from "ImageThumbnail" column of the dataset. I could do it using looping through all rows in DataTable, but I believe there must be some efficient method.

Was it helpful?

Solution

After quickly trying this for myself, it appears to me that this boils down to trying to get the values from a single DataColumn in an efficient way. After I realised this I found this post which suggested 2 solutions. I applied these to my test for ImageLists and I have included my code below:

DataTable dt = new DataTable();
dt.Columns.Add("Name", typeof(String));
dt.Columns.Add("Image", typeof(Image));

dt.Rows.Add("Img1", Properties.Resources.Img_1);
dt.Rows.Add("Img2", Properties.Resources.Img_2);
dt.Rows.Add("Img3", Properties.Resources.Img_3);
dt.Rows.Add("Img4", Properties.Resources.Img_4);

ImageList imgList = new ImageList();

//// Loop Approach:
//for (int idx = 0; idx < dt.Rows.Count; idx++)
//{
//    imgList.Images.Add(dt.Rows[idx]["Image"] as Image);
//}

// LINQ Approach:
imgList.Images.AddRange(dt.Rows.Cast<DataRow>().Select(row => row["Image"] as Image).ToArray());

In my opinion the LINQ Approach is more succinct, but the Loop Approach is perhaps quicker to understand and so is more readable. I am not sure which of these is going to be more efficient, or if they both end up with similar IL code. However, the LINQ Approach uses the AddRange and ToArray built-in methods which could include efficiency improvements (or may do in the future).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top