使用LINQ,我可以验证属性是否具有所有对象的相同值?

JSp*_*ang 27 c# 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;
    }
Run Code Online (Sandbox Code Playgroud)

我很好奇是否可以在LINQ查询中执行?

在此先感谢您的帮助!

dic*_*d30 60

我相信这会奏效:

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

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

  • 优雅的解决方案.但Distinct()强制对所有项进行迭代,并在内部强制进行某种排序.如果您知道列表中的项目很少,那就可以了.如果列表很大或者使用了Validate方法,那么你应该尝试Stecya的消化. (3认同)

Ste*_*cya 16

试试这个

var pixelsWide = rate.Sections.Values.First().PixelsWide;
bool result = crate.Sections.Values.All(x => x.PixelsWide == pixelsWide);
Run Code Online (Sandbox Code Playgroud)

  • 如果没有项目则引发异常. (4认同)
  • 嗯,作为一个扩展方法会很棒,例如:IEnumerable <>.AllSame(propertyName) (3认同)
  • 然后检查是否没有物品并返回"false" (2认同)

Gab*_*abe 7

这是Stecya答案的变体,它不会为空集合抛出异常.

var first = crate.Sections.Values.FirstOrDefault();
bool result = crate.Sections.Values.All(x => x.PixelsWide == first.PixelsWide);
Run Code Online (Sandbox Code Playgroud)