【问题标题】:Linq Count is returning different resultsLinq Count 返回不同的结果
【发布时间】:2015-07-14 16:52:45
【问题描述】:

我有一个数据表,它有两行几列,其中一列是 ABC。我已经验证了数据行确实存在并且所有值都设置正确,但是下面的两行会产生不同的结果:

            //r3 =1
            var r3 = dt.Select().Where(o => o["ABC"] == cls).Count();

            //r4 =2 (correct)
            var r4 = dt.Select().Count(o => o["ABC"].Equals(cls));

我尝试了第二个选项只是一个侥幸,但肯定这些应该做同样的事情吗?

【问题讨论】:

    标签: linq ado.net


    【解决方案1】:

    使用String.Equals 而不是Object.ReferenceEquals(对象上的== 运算符):

    int count = dt.AsEnumerable().Count(r => r.Field<string>("ABC") == cls);
    

    这是一个演示此问题的示例,并且还显示了字符串实习何时绕过它。

    测试表:

    var dt = new DataTable();
    dt.Columns.Add("ABC");
    dt.Rows.Add("Test");
    dt.Rows.Add("Test");  // note that C# is case sensitive, maybe this is another issue
    dt.Rows.Add("test");
    

    第一个字符串is interned,因为它是字符串字面量,所以从池中已有的字符串中复用。第二个字符串是使用不使用string pool 的字符串构造函数创建的。

    string cls1 = "test";   // uses string pool
    string cls2 = new string("test".ToCharArray()); // skips pool
    int count = dt.AsEnumerable().Count(r => r.Field<string>("ABC") == cls2); // 1
    count =  dt.Select().Where(o => o["ABC"] == cls1).Count();  // 1
    count = dt.Select().Where(o => o["ABC"] == cls2).Count();   // 0
    

    所以如果你使用==比较字符串,那么两者都应该是字符串。

    【讨论】:

    • 感谢蒂姆,这是非常晦涩的行为。
    猜你喜欢
    • 2018-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-30
    • 1970-01-01
    相关资源
    最近更新 更多