FindAll 在自定义对象列表中
好吧,我有一个名为 Mamamia 的对象,它的内部有一些字符串属性。我创建了该对象的列表并填充了 150 个项目。
我正在尝试使用 List.FindAll 但我真的不知道该怎么做。我尝试过这种方式:
produto = products.FindAll(delegate(Mamamia cv) {return cv.LocalPackage.Remove(1,21) == cmbPackage.SelectedValue};
我不知道为什么代表在那里,我只是尝试从互联网上的其他代码复制。
提前致谢!
Well, I got an object called Mamamia and inside of it has some string properties. I created a list of this object and populated it with 150 items.
I'm trying to use List.FindAll but I reaaally don't know how to do it. I've tried this way:
produto = products.FindAll(delegate(Mamamia cv) {return cv.LocalPackage.Remove(1,21) == cmbPackage.SelectedValue};
I don't know why the delegate is there, I just tried to copy from some other code on the internet.
Thanks in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
委托的作用是查看您正在测试的值是否是您正在寻找的值。不过,对
Remove
的调用看起来令人担忧,就像它正在改变值一样 - 当您查看列表时,这很少是一件好事。我想如果它是一个字符串那么它还不错,尽管它可能不是你想要的......涉及的类型是什么,你在寻找什么?哦,您使用的是 C# 3 和/或 .NET 3.5 吗?这会让事情变得更容易(即使是针对 .NET 2.0 的 C# 3 也意味着您可以使用 lambda 表达式而不是匿名方法)。
当你现在运行代码时发生了什么?如果它没有找到任何东西,可能只是因为您正在测试引用相等性(如果
SelectedValue
返回object
)。试试这个:
编辑:
听起来您只想要一个值,如果您使用 .NET 3.5,那么首先使用 LINQ 会更惯用。我会用:
The delegate is there to see whether the value that you're testing is what you're looking for. The call to
Remove
looks worryingly like it's mutating the value though - that's rarely a good thing when you're looking through the list. I guess if it's a string then it's not too bad, although it may not be what you're after...What are the types involved, and what are you looking for? Oh, and are you using C# 3 and/or .NET 3.5? That would make it easier (even C# 3 against .NET 2.0 means you could use a lambda expression instead of an anonymous method).
What's happening when you run the code at the moment? If it's just not finding anything, it may just be because you're testing for reference equality (if
SelectedValue
returnsobject
).Try this:
EDIT:
It sounds like you only want a single value, and if you're using .NET 3.5 it would be more idiomatic to use LINQ in the first place. I would use: