Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using LINQ, can I verify a property has the same value for all objects?

Tags:

c#

linq

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!

like image 883
JSprang Avatar asked Mar 29 '11 20:03

JSprang


People also ask

What types of Objects can you query using LINQ?

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.

What are the uses of LINQ to Objects?

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.


2 Answers

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).

like image 130
diceguyd30 Avatar answered Sep 28 '22 12:09

diceguyd30


Try this

var pixelsWide = rate.Sections.Values.First().PixelsWide; bool result = crate.Sections.Values.All(x => x.PixelsWide == pixelsWide); 
like image 25
Stecya Avatar answered Sep 28 '22 13:09

Stecya