表达式不能包含lambda表达式Linq

时间:2015-05-25 06:47:10

标签: c# linq lambda sum

enter image description here

我有数据表,我正在尝试查找Id以特殊值开头的列的总和。我尝试了一些方法,但收到错误。

result=Convert.ToInt32(dtNew.Compute("Sum(ResPending)", "Substring(ID,0,1)='G'"));//error shows-- Substring() argument is out of range

并尝试过这种方式

dtNew.AsEnumerable().Where(x => x.Field<string>("ID").ToString().StartsWith("G"));//Expression can not contain lambda expression

3 个答案:

答案 0 :(得分:2)

result = Convert.ToInt32(dt.Compute("sum(ResPending)", "ID LIKE 'G*'"));

//这对我有用。

dtNew.AsEnumerable().Where(x => x.Field<string>("ID").ToString().StartsWith("G"));

这也有效。

以下是测试代码:

 Random ran = new Random();
        DataTable dt = new DataTable();
        dt.Columns.Add("ID");
        dt.Columns.Add("Name");
        dt.Columns.Add("ResPending", typeof(Int32));
        for (int i = 0; i < 11; i++)
        {
            DataRow dr = dt.NewRow();
            if (i % 2 == 0)
            {
                dr[0] = "G123" + i;
            }
            else
            {
                dr[0] = i;
            }

            dr[1] = "an";
            dr[2] = ran.Next(1, 100);
            dt.Rows.Add(dr);
        }

        int result = 0;
        //// result =  Convert.ToInt32(dt.Compute("sum(ResPending)", "ID LIKE 'G*'"));
        ////result   = Convert.ToInt32(dt.Compute("Sum(ResPending)", "Substring(ID,0,1)='G'")); ////this throws error. as index is 1 based
        var k  = dt.AsEnumerable().Where(x => x.Field<string>("ID").ToString().StartsWith("G"));

答案 1 :(得分:2)

您需要使用

Substring(ID,1,1) 

答案 2 :(得分:0)

此示例代码返回3 | Date | GroupID | Channel | isFirst | isLast | ChannelsInGroup | DaysBeforeLast | |------------|---------|---------|---------|--------|-----------------|----------------| | 2015-02-24 | 1 | A | TRUE | FALSE | 3 | 3 | | 2015-02-26 | 1 | B | FALSE | FALSE | 3 | 1 | | 2015-02-27 | 1 | C | FALSE | TRUE | 3 | 0 | | 2015-03-21 | 2 | D | TRUE | TRUE | 1 | 0 | | 2015-02-20 | 3 | E | TRUE | FALSE | 2 | 5 | | 2015-02-25 | 3 | D | FALSE | TRUE | 2 | 0 | | 2015-02-28 | 4 | C | TRUE | TRUE | 1 | 0 | | 2015-03-04 | 5 | B | TRUE | FALSE | 6 | 19 | | 2015-03-05 | 5 | E | FALSE | FALSE | 6 | 18 | | 2015-03-10 | 5 | D | FALSE | FALSE | 6 | 13 | | 2015-03-11 | 5 | A | FALSE | FALSE | 6 | 12 | | 2015-03-14 | 5 | C | FALSE | FALSE | 6 | 9 | | 2015-03-23 | 5 | F | FALSE | TRUE | 6 | 0 | | 2015-03-28 | 6 | E | TRUE | TRUE | 1 | 0 |

DataRows

这是你想要的吗?