I have data-table and i am trying to find sum of columns where Id starts with Particular value.I have tried some ways but getting error.
result=Convert.ToInt32(dtNew.Compute("Sum(ResPending)", "Substring(ID,0,1)='G'"));//error shows-- Substring() argument is out of range
And tried this way also
dtNew.AsEnumerable().Where(x => x.Field<string>("ID").ToString().StartsWith("G"));//Expression can not contain lambda expression
result = Convert.ToInt32(dt.Compute("sum(ResPending)", "ID LIKE 'G*'"));
//this works for me.
dtNew.AsEnumerable().Where(x => x.Field<string>("ID").ToString().StartsWith("G"));
this also works.
Below is the test code:
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"));
您需要使用
Substring(ID,1,1)
This sample code returns 3 DataRows
:
var coll = dt.AsEnumerable().Where(k => k.Field<string>(0).Contains("G")).Select(p => p).ToList();
Is this what you want?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.