查找整数列表中是否存在整数
我有这个代码:
List<T> apps = getApps();
List<int> ids;
List<SelectListItem> dropdown = apps.ConvertAll(c => new SelectListItem
{
Selected = ids.Contains(c.Id),
Text = c.Name,
Value = c.Id.ToString()
}).ToList();
ids.Contains
即使数字确实符合
任何想法,似乎总是返回 false?
i have this code:
List<T> apps = getApps();
List<int> ids;
List<SelectListItem> dropdown = apps.ConvertAll(c => new SelectListItem
{
Selected = ids.Contains(c.Id),
Text = c.Name,
Value = c.Id.ToString()
}).ToList();
ids.Contains
seems to always return false even though the numbers do match
any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
如果您只需要 true/false 结果,
如果列表中不存在 intVariable 它将返回 -1
If you just need a true/false result
if the intVariable does not exist in the List it will return -1
只要您的列表是用值初始化的,并且该值实际上存在于列表中,那么 Contains 就应该返回 true。
我尝试了以下操作:
并且存在确实设置为true。
As long as your list is initialized with values and that value actually exists in the list, then Contains should return true.
I tried the following:
And exists is indeed set to true.
这是一个扩展方法,它允许像 SQL IN 命令一样进行编码。
这允许这样的事情:
或者:
Here is a extension method, this allows coding like the SQL IN command.
This allows stuff like that:
Or:
你的做法是正确的。它与该代码配合良好: x 为 true。
可能你在其他地方犯了错误。
The way you did is correct. It works fine with that code: x is true.
probably you made a mistake somewhere else.
最好的完整代码在这里:
使用:
The best of code and complete is here:
Use:
您应该引用
Selected
而不是ids.Contains
作为最后一行。我刚刚意识到这是来自OP的格式问题。无论如何,您应该引用 Selected 中的值。我建议添加一些 Console.WriteLine 调用,以准确查看每行打印的内容以及每个值是什么。
更新后:
ids 是一个空列表,这怎么会不抛出 NullReferenceException 呢?因为它从未在该代码块中初始化
You should be referencing
Selected
notids.Contains
as the last line.I just realized this is a formatting issue, from the OP. Regardless you should be referencing the value in Selected. I recommend adding some Console.WriteLine calls to see exactly what is being printed out on each line and also what each value is.
After your update:
ids is an empty list, how is this not throwing a NullReferenceException? As it was never initialized in that code block