yonan2236 yonan2236 - 4 months ago 17
C# Question

How to do this in lambda expression or linq?

I have this requirement,

A product can have multiple images and only one default image. You can determine the default image of the product if the property

is equal to true.

I want to do it in LINQ and lambda but I'm stucked in my code:

private class ProdcutImages
public Int32 ID { get; set; }
public String ProductID { get; set; }
public Boolean IsDefault { get; set; }
public Image Image { get; set; }
public String FileName { get; set; }

public void SetDefaultImage(int productID)
SqlConnection conn = getConnection();
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM product_images WHERE product_id = @ID", conn);
da.SelectCommand.Parameters.Add(new SqlParameter("@ID", productID));

DataTable dt = new DataTable();

var imageList = (from tr in dt.AsEnumerable()
select new ProdcutImages()
ID = tr.Field<int>("id"),
ProductID = tr.Field<string>("productId"),
IsDefault = tr.Field<bool>("isDefault"),
Image = tr.Field<Image>("image"),
FileName = tr.Field<string>("fileName")

pictureBox1.Image = // ???


probably this:

var img = imageList.FirstOrDefault(i => i.IsDefault);
if (img != null) { pictureBox1.Image = img.Image; }

or, to take into account the case someone forgot to set the IsDefault field on any image:

var img = imageList.FirstOrDefault(i => i.IsDefault) ?? imageList.FirstOrDefault();
if (img != null) { pictureBox1.Image = img.Image; }

(this would use the first available image if none is set as default)