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; }
I'm curious if this would be possible to execute in a LINQ query?
Thanks in advance for any help!
You can use LINQ to query any enumerable collections such as List<T>, Array, or Dictionary<TKey,TValue>. The collection may be user-defined or may be returned by a . NET API. In a basic sense, LINQ to Objects represents a new approach to collections.
In a nutshell, LINQ to Objects provides the developer with the means to conduct queries against an in-memory collection of objects. The techniques used to query against such collections of objects are similar to but simpler than the approaches used to conduct queries against a relational database using SQL statements.
I believe this would work:
public bool Validate(Crate crate) { return crate.Sections .Select(x => x.Value.PixelsWide) .Distinct() .Count() < 2; }
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).
Try this
var pixelsWide = rate.Sections.Values.First().PixelsWide; bool result = crate.Sections.Values.All(x => x.PixelsWide == pixelsWide);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With