如何在lambda表达式或linq中执行此操作? [英] How to do this in lambda expression or linq?
本文介绍了如何在lambda表达式或linq中执行此操作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个要求,
一个产品可以有多个图像,并且只能包含一个默认图像.如果属性isDefault
等于true,则可以确定产品的默认图像.
A product can have multiple images and only one default image. You can determine the default image of the product if the property isDefault
is equal to true.
我想用LINQ和lambda来做,但是我被卡在代码里:
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();
conn.Open();
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();
da.Fill(dt);
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")
}).ToList();
pictureBox1.Image = // ???
conn.Close();
}
推荐答案
可能是这样:
var img = imageList.FirstOrDefault(i => i.IsDefault);
if (img != null) { pictureBox1.Image = img.Image; }
或者,考虑到有人忘记在任何图像上设置IsDefault字段的情况:
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)
这篇关于如何在lambda表达式或linq中执行此操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文