c# - 字典c#的算术运算

标签 c# linq dictionary redis hashtable

我有这个字典对象:- Dictionary<string,string> lstTransList;

此对象的值为 |Key={Id}|Value={|QTY=4|PICKEDUP=2}|

enter image description here

现在我想计算记录数,每条记录的 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/

相关文章:

javascript - javascript 中的 C# DateTime.MaxValue 等效项

c# - 在 C# 中单击数据库中的按钮加载前 20 个项目,然后加载接下来的 20 个项目

c# - 如何使用c#检查硬盘是Sata设备还是IDE设备

c# - 工作 LINQ 查询在单元测试中不起作用

c# - 在 LINQ to SQL 中选择 "IN"

python - 使用python函数在字典中按值获取键并返回键或 "None'

c# - MySQL(和c#?)转换字符格式

c# - 查询的多个要求

Python-如何比较字典列表上 FOR 循环中 IF 语句中的键值?

arrays - 如何更改数组字典中元素的值?