[英]Arithmetic operations on dictionary c#
我有这个字典对象为: Dictionary<string,string> lstTransList;
该对象的值为|Key={Id}|Value={|QTY=4|PICKEDUP=2}|
现在我想计算记录数,每条记录的QTY和PICKEDUP之差,然后求和,求和PICKEDUP和差之和。 是否有使用LINQ执行这些算术运算的有效方法?
我得到的计数为: int total_transactiondone = lstTransList.Count();
对于QTY的求和,我想使用Keys作为“ QTY”和“ PICKEDUP”来拆分字典对象的值,但不知道如何使用它。 有什么建议么 ??
考虑使用这样的东西:
decimal total_tickets = lstTransList.Sum(x => Convert.ToDecimal(x.Value));
编辑:
现在,我正在使用Followin方法来完成此任务。 还有其他有效的方法吗? 请提出建议。
var lstTransList = objRedis.GetAllEntriesFromHash(strHashey);
DataTable dtTransList = new DataTable();
dtTransList.Columns.Add("TransId");
dtTransList.Columns.Add("Qty", typeof(int));
dtTransList.Columns.Add("PickedUp", typeof(int));
dtTransList.Columns.Add("UnPickedUp", typeof(int));
foreach (KeyValuePair<string, string> entry in lstTransList)
{
DataRow DR = dtTransList.NewRow();
if (!string.IsNullOrEmpty(entry.Key))
{
DR[0] = entry.Key;
}
if (!string.IsNullOrEmpty(entry.Value))
{
clsKeyValueParser objKV = new clsKeyValueParser(entry.Value);
DR[1] = Convert.ToInt32(objKV.strGetValue("QTY", "0"));
DR[2] = Convert.ToInt32(objKV.strGetValue("PICKEDUP", "0"));
DR[3] = Convert.ToInt32(DR[1]) - Convert.ToInt32(DR[2]);
}
dtTransList.Rows.Add(DR);
}
int total_transactiondone = dtTransList.Rows.Count;
int total_tickets = dtTransList.AsEnumerable().Sum(x => x.Field<int>(1));
int total_ticketsunpickedup = dtTransList.AsEnumerable().Sum(x => x.Field<int>(3));
int total_pickeduptransaction = dtTransList.AsEnumerable().Count(row => row.Field<int>(3) == 0);
int total_unpickeduptransaction = dtTransList.AsEnumerable().Count(row => row.Field<int>(3) != 0);
尝试此操作以获得总计的数量
decimal total_tickets_qty = lstTransList.Sum(x => Convert.ToDecimal(Regex.Match(x.Value.Split('|')[1], @"\d+").Value);
提货总额
decimal total_tickets_pickedup = lstTransList.Sum(x => Convert.ToDecimal(Regex.Match(x.Value.Split('|')[2], @"\d+").Value));
差异总计
decimal total_tickets = lstTransList.Sum(x => Convert.ToDecimal(Regex.Match(x.Value.Split('|')[1], @"\d+").Value) - Convert.ToDecimal(Regex.Match(x.Value.Split('|')[2], @"\d+").Value));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.