首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在MVC中实现MB值和GB值字段的求和函数

如何在MVC中实现MB值和GB值字段的求和函数
EN

Stack Overflow用户
提问于 2018-08-11 19:00:00
回答 1查看 60关注 0票数 -1

我的字段值如下:

810.9 MB
1.2 GB
395.1 MB
982.3 MB
7.7 GB
149.4 MB
10.0 GB
429.1 MB
3.1 GB

我想在我的ASP.NET MVC控制器中以gb为单位对这一列求和。

但我不知道该怎么做。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-08-11 20:32:53

您可以尝试如下所示:

-- This is your "raw" input - just all the strings in your example
DECLARE @input TABLE (Measure VARCHAR(50))

INSERT INTO @input ( Measure )
VALUES ('810.9 MB'), ('1.2 GB'), ( '395.1 MB'), ( '982.3 MB'), ( '7.7 GB'), ( '149.4 MB'), ( '10.0 GB'), ( '429.1 MB'), ( '3.1 GB')

-- Now declare a separate table that contains (1) the raw value, (2) the contained *numerical* value, and (3) the unit of measure
DECLARE @Storage TABLE (Measure VARCHAR(50), NumValue DECIMAL(20,4), Unit VARCHAR(10))

-- Fill your raw input into that "working table"
INSERT INTO @Storage (Measure, NumValue, Unit)
    SELECT
        Measure,
        NumMeasure = CAST(SUBSTRING(Measure, 1, CHARINDEX(' ', Measure)) AS DECIMAL(20, 2)),
        Unit = SUBSTRING(Measure, CHARINDEX(' ', Measure) + 1, 9999)
    FROM 
        @input

SELECT * FROM @Storage

-- when you select from that "working" table, you can now easily *SUM* the numerical values,
-- and show them on screen whichever way you want - as "xxx MB" or "yyyy GB" or whatever - up to you
SELECT 
    SUM(CASE Unit   
           WHEN 'MB' THEN NumValue * 1000000
           WHEN 'GB' THEN NumValue * 1000000000
           ELSE NumValue
        END),
    CAST(SUM(CASE Unit   
           WHEN 'MB' THEN NumValue * 1000000
           WHEN 'GB' THEN NumValue * 1000000000
           ELSE NumValue
        END) / 1000000000.0 AS VARCHAR(25)) + ' GB'
FROM 
    @Storage

更新:

如果您想在C#代码中执行此操作,请尝试执行以下操作:

foreach(var item in list)
{
    // split "item" into two parts
    string[] parts = item.Split(' ');

    // parts[0] should be a decimal value
    decimal numValue = 0.0m;

    if (decimal.TryParse(parts[0], out numValue))
    {
        decimal convertedValue = 0.0m;

        if(parts[1] == "MB")
        {
            convertedValue = numValue * 1000000;
        }
        else if (parts[1] == "GB")
        {
            convertedValue = numValue * 1000000000;
        }
     }
}    
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51798988

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档