我有这个字典对象:- Dictionary<string,string> lstTransList;
此对象的值为 |Key={Id}|Value={|QTY=4|PICKEDUP=2}|
现在我想计算记录数,每条记录的 QTY 和 PICKEDUP 的差值,然后是 QTY 的总和,PICKEDUP 的总和和差值的总和。 有没有使用 LINQ 执行这些算术运算的有效方法?
我算作:- int total_transactiondone = lstTransList.Count();
对于 QTY 的总和,我想使用键将字典对象的值拆分为“QTY”和“PICKEDUP”,但不知道如何使用它。有什么建议吗??
想用这样的东西:
decimal total_tickets = lstTransList.Sum(x => Convert.ToDecimal(x.Value));
编辑:
现在我正在使用以下方法来完成这项任务。还有其他有效的方法吗?请提出建议。
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);
PICKEDUP 总数
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));
关于c# - 字典c#的算术运算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35773077/