使用LINQ,我可以验证一个属性对所有对象相同的值? [英] Using LINQ, can I verify a property has the same value for all objects?

查看:82
本文介绍了使用LINQ,我可以验证一个属性对所有对象相同的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个木板箱对象,它具有KeyValuePairs的List。目前,我通过遍历每一对,看是否kvp.Value.PixelsWide是列表中的所有项目一样。如果是这样,返回true,否则返回false。

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;
    }



我很好奇,如果这是有可能的LINQ查询来执行?

I'm curious if this would be possible to execute in a LINQ query?

在您的帮助谢谢!

推荐答案

我相信这将工作:

public bool Validate(Crate crate)
{
    return crate.Sections
                .Select(x => x.Value.PixelsWide)
                .Distinct()
                .Count() < 2;
}

这将返回true,如果 crate.Sections 是空的,以及当元素都是相同的(这是您当前函数的行为)。

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).

这篇关于使用LINQ,我可以验证一个属性对所有对象相同的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆