我有一个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 .
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)
这是Stecya答案的变体,它不会为空集合抛出异常.
var first = crate.Sections.Values.FirstOrDefault();
bool result = crate.Sections.Values.All(x => x.PixelsWide == first.PixelsWide);
Run Code Online (Sandbox Code Playgroud)