0

尝试使用 linq 计算列值。它正确求和,但在除法或乘法时产生不正确的值。示例如下。

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
        DataTable dtWidgets = Get_widgets();   
        DataTable dtHits = Get_hits();

        var hit_rate =
        from w in dtWidgets.AsEnumerable()
        join h in dtHits.AsEnumerable()
            on w[0] equals h[0]
        select new
        {
            Date = w.Field<DateTime>("calendar_date"),
            Widgets = w.Field<int>("widgets"),
            Hits = h.Field<int>("hits"),
            TestSum = w.Field<int>("widgets")+h.Field<int>("hits"),
            TestMult = w.Field<int>("widgets") * h.Field<int>("hits")
        };

        gvWidgets.DataSource = dtWidgets;
        gvWidgets.DataBind();

        gvHits.DataSource = dtHits;
        gvHits.DataBind();

        gvLinq.DataSource = hit_rate.ToArray();
        gvLinq.DataBind();

    }

    static DataTable Get_widgets()
    {
        DataTable widgets = new DataTable();
        widgets.Columns.Add("calendar_date", typeof(DateTime));
        widgets.Columns.Add("widgets", typeof(int));

        widgets.Rows.Add("05/15/2012", 200000);
        widgets.Rows.Add("05/16/2012", 210000);
        return widgets;
    }

    static DataTable Get_hits()
    {
        DataTable hits = new DataTable();
        hits.Columns.Add("calendar_date", typeof(DateTime));
        hits.Columns.Add("hits", typeof(int));

        hits.Rows.Add("05/15/2012", 100000000);
        hits.Rows.Add("05/16/2012", 120000000);
        return hits;
    }
}

回报:

日期小部件命中 TestSum TestMult

5/15/2012 12:00:00 AM 200000 100000000 100200000 -1662697472

2012 年 5 月 16 日上午 12:00:00 210000 120000000 120210000 1426874368

4

2 回答 2

1

鉴于您在代码下方列出的示例数字,看起来您正在获得整数溢出。尝试将字段类型设为 Int64。

于 2012-05-25T22:43:26.867 回答
0

如果我在哪里,我会查看 c# 中 int 的限制... (2147483647)

尝试使用 long (= Int64)

20000000000000 
>
2147483647
于 2012-05-25T22:43:47.760 回答