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

我有一个Crate对象,它有一个KeyValuePairs列表。 目前,我正在遍历每一对,以查看列表中所有项目的kvp.Value.PixelsWide是否相同。 如果是,则返回true,否则返回false。

我现有的方法如下所示:

public bool Validate(Crate crate) { int firstSectionWidth = 0; foreach (KeyValuePair 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。

试试这个

 var pixelsWide = rate.Sections.Values.First().PixelsWide; bool result = crate.Sections.Values.All(x => x.PixelsWide == pixelsWide); 

这是Stecya答案的变体,它不会为空集合抛出exception。

 var first = crate.Sections.Values.FirstOrDefault(); bool result = crate.Sections.Values.All(x => x.PixelsWide == first.PixelsWide); 

如果您不介意遍历整个集合:

 bool hasOneValue = crate.Sections.Select(s => s.Value.PixelsWide).Distinct().Count() == 1; 

或者使其与您的代码保持一致:

 bool validateResult = crate.Sections.Select(s => s.Value.PixelsWide).Distinct().Count() <= 1; 

分组太慢了?

 public bool Validate(Crate crate) { return crate.GroupBy(c => c.Value.PixelsWide).Count() < 2; } 

我和@Stecya在一起:

 public class Crate { IList> Sections ; public bool IsValid() { return Sections.All( x => x.Value.PixelsWide == Sections.FirstOrDefault().Value.PixelsWide ) ; } public class SectionConfiguration { public int PixelsWide ; } } 

我的版本:

 public bool Validate(Crate crate) { return !crate.Sections .Any(a => crate.Sections .Where(b => b.Value.PixelsWide != a.Value.PixelsWide).Any() ); }