如果可能,我想优化此查询并减少循环数。至少我必须首先选择所有客户端 ID 以进行迭代。任何帮助表示赞赏。
public DataTable convertCollectionExpectedToDatatable(List<Invoice> lst)
{
DataTable dtcollection = new DataTable();
try
{
dtcollection.Columns.Add("ClientId", typeof(string));
dtcollection.Columns.Add("customerName", typeof(string));
dtcollection.Columns.Add("BalAmnt1", typeof(string));
dtcollection.Columns.Add("BalAmnt2", typeof(string));
dtcollection.Columns.Add("BalAmnt3", typeof(string));
dtcollection.Columns.Add("totalAmt", typeof(string));
DateTime promiseDate1 = DateTime.Today;
DateTime promiseDate2 = promiseDate1.AddDays(1);
DateTime promiseDate3 = promiseDate2.AddDays(1);
var select = (from l in lst select l.ClientId).Distinct();
List<long> lstInv = select.ToList<long>();
DataRow dr;
foreach (long inv in lstInv)
{
decimal BalAmnt1 = lst.Where(Invoice => Invoice.ExpDt ==
promiseDate1 && Invoice.ClientId == inv).Select(Invoice => Invoice.BalAmnt).Sum();
decimal BalAmnt2 = lst.Where(Invoice => Invoice.ExpDt ==
promiseDate2 && Invoice.ClientId == inv).Select(Invoice => Invoice.BalAmnt).Sum();
decimal BalAmnt3 = lst.Where(Invoice => Invoice.ExpDt ==
promiseDate3 && Invoice.ClientId == inv).Select(Invoice => Invoice.BalAmnt).Sum();
var clientName = (from l in lst where l.ClientId == inv select
l.Client.Name).FirstOrDefault();
dr = dtcollection.NewRow();
dr["ClientId"] = inv.ToString();
dr["customerName"] = clientName.ToString();
dr["BalAmnt1"] = string.Format("{0:n2}", BalAmnt1);
dr["BalAmnt2"] = string.Format("{0:n2}", BalAmnt2);
dr["BalAmnt3"] = string.Format("{0:n2}", BalAmnt3);
dr["totalAmt"] = string.Format("{0:n2}", BalAmnt1 + BalAmnt2 +
BalAmnt3);
dtcollection.Rows.Add(dr);
}
}