cmd = new SqlCommand(" ", con);
da = new SqlDataAdapter(cmd);
DataTable t_eight = new DataTable("t_eight");
da.Fill(t_eight); //databale "t_eight" fill
//linq query
var query3 = (from a in t_eight.AsEnumerable() //t_eigth Databale
group a by new
{ //Group by with condition
IdendityName = a.Field<String>("Idendity Name"),
ContactPersonName = a.Field<String>("Contact Person Name"),
CustomerName = a.Field<String>("Customer Name")
}
into g
select new
{
IdendinyName = g.Key.IdendityName,
ContactPersonName = g.Key.ContactPersonName,
CurtomerName = g.Key.CustomerName,
TotalBook = g.Sum(x => x.Field<Int32>("Total Book Quantity")
+ x.Field<Int32>("Quatan Book Qty")
- x.Field<Int32>("Return Book Quality"))
});
GridView1.DataSource = query3;
GridView1.DataBind();
数据表包含“身份名称”,“客户名称”,“客户联系人姓名”,“总账簿数量”,“退货手册质量”和“Quatan手册数量”等列。
分组依据包含三列标识名称,客户名称和客户联系人姓名
select语句中的新列Total Book包含(书籍总量+ Quatan Book Qty-Return Book Quality)。我想要gridview中的所有列,但网格包含身份名称,客户名称,客户联系人姓名和总帐簿列
我该怎么做?
答案 0 :(得分:0)
假设您希望在对行进行分组后其他字段相同,您只需从组中选择一个随机行来获取值 - First
行应该有效。
var query3 = (from a in t_eight.AsEnumerable()//t_eigth Databale
group a by new
{//Group by with condition
IdendityName = a.Field<String>("Idendity Name"),
ContactPersonName = a.Field<String>("Contact Person Name"),
CustomerName = a.Field<String>("Customer Name")
}
into g
select new {
g.Key.IdendityName,
g.Key.ContactPersonName,
g.Key.CustomerName,
ReturnBookQuality = g.First().Field<Int32>("Return Book Quality"),
QuatanBookQty = g.First().Field<Int32>("Quatan Book Qty"),
TotalBook = g.Sum(x => x.Field<Int32>("Total Book Quantity")
+ x.Field<Int32>("Quatan Book Qty") - x.Field<Int32>("Return Book Quality"))
}
);
注意:我从匿名类型中删除了冗余的成员名称,我没有看到任何理由将它们放在那里。
答案 1 :(得分:0)
如果我理解正确,您希望在计算的TotalBook
列之外看到三列的总数。以下是您可以这样做的方法:
var query3 = (from a in t_eight.AsEnumerable()
group a by new
{
IdendityName = a.Field<String>("Idendity Name"),
ContactPersonName = a.Field<String>("Contact Person Name"),
CustomerName = a.Field<String>("Customer Name")
}
into g
let tbq = g.Sum(x => x.Field<Int32>("Total Book Quantity"))
let qbq = g.Sum(x => x.Field<Int32>("Quatan Book Qty"))
let rbq = g.Sum(x => x.Field<Int32>("Return Book Quality"))
select new
{
IdendinyName = g.Key.IdendityName,
ContactPersonName = g.Key.ContactPersonName,
CurtomerName = g.Key.CustomerName,
TotalBookQuantity = tbq,
QuatanBookQuantity = qbq,
ReturnBookQuantity = rbq,
TotalBook = tbq + qbq - rbq
});
三个let
语句收集每个分组的各个总和,之后您可以多次使用变量tbq
等。