试图使用单一条件排序数据网格视图列
本文关键字:数据网 数据 网格 视图 排序 条件 单一 | 更新日期: 2023-09-27 18:07:09
我使用下面的函数,如果我单击数据网格视图列标题,整个数据网格视图列将被排序....
private void dgvproducts_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
if (order == "d")
{
//order by ascending
order = "a";
dgvproducts.DataSource = dbcontext.products
.GroupBy(x => x.product_Id)
.Select(a => new
{
productid = a.Key,
prouctnam = a.FirstOrDefault().product_Name,
productimage = a.FirstOrDefault().product_Image,
productdescr = a.FirstOrDefault().product_Description,
stockavailable = a.LongCount(),
productprice = a.FirstOrDefault().product_Price
}).OrderBy(a=>a.prouctnam).ToList();
}
else
{
// order by descending
order = "d";
dgvproducts.DataSource = dbcontext.products
.GroupBy(x => x.product_Id)
.Select(a => new
{
productid = a.Key,
prouctnam = a.FirstOrDefault().product_Name,
productimage = a.FirstOrDefault().product_Image,
productdescr = a.FirstOrDefault().product_Description,
stockavailable = a.LongCount(),
productprice = a.FirstOrDefault().product_Price
}).OrderByDescending(a => a.prouctnam).ToList();
}
}
this is working fine....
我想要的是,是否有可能检查单一条件和绑定数据网格视图一次…
而不是做两次......
提前感谢大家的意见....
您可以重构并只在以后应用顺序部分—这样可以避免大多数重复代码:
var products = dbcontext.products
.GroupBy(x => x.product_Id)
.Select(a => new
{
productid = a.Key,
prouctnam = a.FirstOrDefault().product_Name,
productimage = a.FirstOrDefault().product_Image,
productdescr = a.FirstOrDefault().product_Description,
stockavailable = a.LongCount(),
productprice = a.FirstOrDefault().product_Price
});
if (order == "d")
{
order = "a";
dgvproducts.DataSource = products.OrderBy(a=>a.prouctnam).ToList();
}
else
{
order = "d";
dgvproducts.DataSource = products.OrderByDescending(a=>a.prouctnam).ToList();
}