如何检查一个列表框中的几个选定元素是否可以被 3 整除并且它们是整数?

发布于 2025-01-06 04:52:37 字数 118 浏览 5 评论 0原文

我有一个包含 5 个元素的列表框: 3 猫 狗 4 9

现在我必须检查所选元素是否是整数以及它们是否可以被3整除,如果是我应该对它们求和。谢谢 (例如,选择了 3、狗和 9,我应该将 12 添加到标签中)

I have one listbox with 5 elements:
3
cat
dog
4
9

Now I have to check if the selected elements are integers and if they are divisible by 3, if they are I should sum them.thanks
(where for example, 3, dog and 9 are selected and I should get 12 into a label)

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

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

发布评论

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

评论(2

痴者 2025-01-13 04:52:37

迭代每个元素并使用 int.TryParse。如果可以解析,请检查 intvalue % 3 == 0 以查看它是否可以被 3 整除。

Iterate over each element and use int.TryParse. If it parses, check intvalue % 3 == 0 to see if it's divisible by three.

没有你我更好 2025-01-13 04:52:37

假设您的列表框中的项目位于字符串列表中,这将是解决该问题的 Linq 方法:

List<string> items = new List<string>() { "3", "cat", "dog", "4", "9"};
int sum  = items.Select(x =>
            {
                int intValue;
                return int.TryParse(x, out intValue) ? intValue : 0;
            })
            .Where(x => x % 3 == 0)
            .Sum();

Suppose you have the items from your listbox in a list of strings this would be a Linq approach to the problem:

List<string> items = new List<string>() { "3", "cat", "dog", "4", "9"};
int sum  = items.Select(x =>
            {
                int intValue;
                return int.TryParse(x, out intValue) ? intValue : 0;
            })
            .Where(x => x % 3 == 0)
            .Sum();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文