我有一个箱子对象,其中有一个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查询中执行吗?

在此先感谢您的帮助!

最佳答案

我相信这会起作用:

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

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

10-01 07:59
查看更多