我正在尝试加入3张桌子。
这是我从互联网上找到的一项功能
public DataTable LINQToDataTable<T>(IEnumerable<T> varlist)
{
DataTable dtReturn = new DataTable();
// column names
PropertyInfo[] oProps = null;
if (varlist == null) return dtReturn;
foreach (T rec in varlist)
{
// Use reflection to get property names, to create table, Only first time, others will follow
if (oProps == null)
{
oProps = ((Type)rec.GetType()).GetProperties();
foreach (PropertyInfo pi in oProps)
{
Type colType = pi.PropertyType;
if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition()
== typeof(Nullable<>)))
{
colType = colType.GetGenericArguments()[0];
}
dtReturn.Columns.Add(new DataColumn(pi.Name, colType));
}
}
DataRow dr = dtReturn.NewRow();
foreach (PropertyInfo pi in oProps)
{
dr[pi.Name] = pi.GetValue(rec, null) == null ? DBNull.Value : pi.GetValue
(rec, null);
}
dtReturn.Rows.Add(dr);
}
return dtReturn;
}
这是我的linq
var id = (from u in myDb.TBL_TRANSAKSI_MKN_MNMs
join l in myDb.TBL_DETAIL_TRANSAKSIs on u.ID_NOTA equals l.ID_NOTA
//into g1
join m in myDb.TBL_MKN_MNMs on l.ID_MKN_MNM equals m.ID_MKN_MNM
//into g
group new {u,l,m} by new {u.TGL_TRANSAKSI, m.NAMA_MKN_MNM, m.HARGA_JUAL, l.ID_MKN_MNM, u.USERNAME}
into grp
where grp.Key.TGL_TRANSAKSI.Value.Date.Equals(dateTimePicker1.Value.Date)
select new
{
MakanMinum = grp.Key.NAMA_MKN_MNM,
HargaJual = grp.Key.HARGA_JUAL,
sumStok = grp.Sum(groupedthing => groupedthing.l.ID_MKN_MNM),
Tanggal = grp.Key.TGL_TRANSAKSI,
Jumlah = grp.Key.HARGA_JUAL * grp.Sum(groupedthing => groupedthing.l.ID_MKN_MNM),
Total = grp.Sum(grouptotal => grp.Key.HARGA_JUAL * grp.Sum(groupedthing => groupedthing.l.ID_MKN_MNM)),
Username = grp.Key.USERNAME
});
我有一个排队的foreach(T rec in varlist) 有没有简单的查询.. ??因为我很困惑加入3张桌子...... 谢谢你的进步
答案 0 :(得分:0)
我认为你的问题是: 您的查询结果是匿名类型,因此您应该像这样更改您的代码:
var id = (from u in myDb.TBL_TRANSAKSI_MKN_MNMs
where u.GL_TRANSAKSI.Value.Date.Equals(dateTimePicker1.Value.Date)
join l in myDb.TBL_DETAIL_TRANSAKSIs on u.ID_NOTA equals l.ID_NOTA
//into g1
join m in myDb.TBL_MKN_MNMs on l.ID_MKN_MNM equals m.ID_MKN_MNM
//into g
group new {u,l,m} by new {u.TGL_TRANSAKSI, m.NAMA_MKN_MNM, m.HARGA_JUAL, l.ID_MKN_MNM, u.USERNAME}
into grp
select new MyClass
{
MakanMinum = grp.Key.NAMA_MKN_MNM,
HargaJual = grp.Key.HARGA_JUAL,
sumStok = grp.Sum(groupedthing => groupedthing.l.ID_MKN_MNM),
Tanggal = grp.Key.TGL_TRANSAKSI,
Jumlah = grp.Key.HARGA_JUAL * grp.Sum(groupedthing => groupedthing.l.ID_MKN_MNM),
Total = grp.Sum(grouptotal => grp.Key.HARGA_JUAL * grp.Sum(groupedthing => groupedthing.l.ID_MKN_MNM)),
Username = grp.Key.USERNAME
});
class MyClass
{
public string MakanMinum {get;set;}
.....
}