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