2017-04-03 117 views
-1

我正在使用linq从datagridview中获取列值。有一次我的列值(数字),然后,我要根据范围 这里记录数是我的代码 -如何将C语言中的Var转换为int []#

var column_values = radGridView1.Rows.Cast<Telerik.WinControls.UI.GridViewRowInfo>().Select(r => r.Cells["columnName"].Value); 

int count = 0; 
foreach(int i in columnvalues.ToList()){ 
if(i > 0.1 and i < 0.5) { 
    count++ 
} 
} 

但我收到此错误

无法转换 类型的对象'System.Collection.Generic.List`1 [System.Object]'键入 system.IConvertible'。

我知道foreach条件是错误的,但无法弄清楚。数字也可以是小数。

也有直接的方式来使用linq而不是使用for循环来做到这一点。

请帮忙。

+1

数字如何能同时低于10和高于50? –

+0

'columnvalues'是否意味着与'column_values'相同?你是否想知道任何一个的内容的实际运行时类型? –

+0

变量名称是错字,但在实际代码中是正确的。另外,所有值都是十进制值。 –

回答

0

如果值实际上是整型,你可以用.Cast()

foreach (int i in columvalues.Cast<int>()) 

如果他们是字符串,可以解析它们:

+0

我收到错误 - “指定的演员表与Cast无效”。这些值实际上是十进制值。 –

+0

@jamesandy然后在我的例子中使用'decimal'而不是'int' ... – itsme86

+0

它给出同样的错误。 –

0

只要改变你的选择要使用int.Parse :

Select(r => int.Parse(r.Cells["columnName"].Value.ToString())); 

然后你可以迭代整数,不需要ToList

foreach(var i in columnvalues) 

您也可以通过使用Count方法摆脱foreach

var count = radGridView1.Rows.Cast<Telerik.WinControls.UI.GridViewRowInfo>() 
        .Select(r => int.Parse(r.Cells["columnName"].Value)) 
        .Count(x => (your condition)); 

我离开的条件部分你,因为你得到了条件永远不会有true

+0

我得到错误无法将obj转换为字符串在这里 - int.Parse(r.Cells [“columnName”]。Value) –

+0

@jamesandy在'Value'后面添加'.ToString()'。 –

+0

我得到错误“输入字符串格式不正确” - var count = radGridView1.Rows.Cast () .Select(r => int.Parse(r.Cells [“column名称“] ToString())) .Count(x => x <0。1); –