将字符串转换为foreach loop c#剃刀页

发布于 2025-02-01 04:05:08 字数 863 浏览 1 评论 0原文

我正在使用foreach循环从数据库中检索数据,并且包括带有文本和数字的字段。我需要将带有数字从字符串的字段转换为int,以便能够正确对数字字段进行正确排序。

我从另一个线程尝试了以下内容,但对我不起作用:

 // Displays the value as string  
Convert.ToInt32(item.property);

// Throws an exception error "The best overloaded method match for 'int.TryParse(string out int' has some invalid arguments)"
Int32.TryParse(item.property, out PropertyInt);

以下是:

如何将字符串转换为int?

但这在foreach循环中对我不起作用。

这是我的代码:

@foreach (var item in db.Query(collection))
{
<tr>
<td>item.name</td>
<td>@Convert.ToInt32(item.value);</td>
<td>Int32.TryParse(item.value, out ItemValueInt);</td>
</tr>
}

I am using a foreach loop to retrieve data from database and it includes both fields with text and numbers. I need to convert the fields with numbers from string to int to be able to sort the number fields properly.

I tried the following from another thread but it is not working for me:

 // Displays the value as string  
Convert.ToInt32(item.property);

// Throws an exception error "The best overloaded method match for 'int.TryParse(string out int' has some invalid arguments)"
Int32.TryParse(item.property, out PropertyInt);

Followed following:

How can I convert String to Int?

But this is not working for me in a foreach loop.

Here is my code:

@foreach (var item in db.Query(collection))
{
<tr>
<td>item.name</td>
<td>@Convert.ToInt32(item.value);</td>
<td>Int32.TryParse(item.value, out ItemValueInt);</td>
</tr>
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

許願樹丅啲祈禱 2025-02-08 04:05:08

尝试使用TryParse检查字符串是否可以转换为INT,如果为true,则显示itemValueInt,这是一个演示:

@{ int ItemValueInt;}
@if (Int32.TryParse(item.value, out ItemValueInt))
{
    <td>@ItemValueInt</td>
}

Try to use TryParse to check if the string can be converted to int,and if true, show the ItemValueInt,here is a demo:

@{ int ItemValueInt;}
@if (Int32.TryParse(item.value, out ItemValueInt))
{
    <td>@ItemValueInt</td>
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文