使用 LINQ,我可以验证所有对象的属性都具有相同的值吗?
我有一个 Crate 对象,其中有一个 KeyValuePairs 列表。目前,我正在迭代每一对,以查看列表中所有项目的 kvp.Value.PixelsWide 是否相同。如果是,则返回 true,否则返回 false。
我现有的方法如下所示:
public bool Validate(Crate crate)
{
int firstSectionWidth = 0;
foreach (KeyValuePair<string, SectionConfiguration> kvp in crate.Sections)
{
if (firstSectionWidth == 0)//first time in loop
{
firstSectionWidth = kvp.Value.PixelsWide;
}
else //not the first time in loop
{
if (kvp.Value.PixelsWide != firstSectionWidth)
{
return false;
}
}
}
return true;
}
我很好奇这是否可以在 LINQ 查询中执行?
预先感谢您的任何帮助!
I have a Crate object, which has a List of KeyValuePairs. Currently, I'm iterating through each pair to see if the kvp.Value.PixelsWide are the same for all items in the List. If they are, return true, else false.
The existing method that I have is shown below:
public bool Validate(Crate crate)
{
int firstSectionWidth = 0;
foreach (KeyValuePair<string, SectionConfiguration> kvp in crate.Sections)
{
if (firstSectionWidth == 0)//first time in loop
{
firstSectionWidth = kvp.Value.PixelsWide;
}
else //not the first time in loop
{
if (kvp.Value.PixelsWide != firstSectionWidth)
{
return false;
}
}
}
return true;
}
I'm curious if this would be possible to execute in a LINQ query?
Thanks in advance for any help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
我相信这会起作用:
如果
crate.Sections
为空以及元素全部相同(这是当前函数的行为),这将返回 true。I believe this would work:
This will return true if
crate.Sections
is empty as well as when the elements are all the same (which is the behavior of your current function).试试这个
Try this
这是 Stecya 的 答案不会为空集合引发异常。
Here's a variation on Stecya's answer that doesn't throw an exception for an empty collection.
如果您不介意迭代整个集合:
或者使其与您的代码一致:
If you don't mind iterating through entire collection:
Or making it consistent with your code:
分组太慢了吗?
Is grouping too slow?
我和@Stecya 在一起:
I'm with @Stecya:
我的版本:
My version:
这可以相当简单地实现为扩展方法:
This can be implemented as an extension method fairly trivially:
我的扩展方法如下所示:
并且使用方式如下:
My extension method for this looks like this:
And it is used like this: