This is in someway related to this (Getting all unique Items in a C# list) question.
The above question is talking about a simple array of values though. I have an object returned from a third party web service:
public class X
{
public Enum y {get; set;}
}
I have a List of these objects List<x> data;
, about 100 records in total but variable. Now I want all the possible values in the list of the property y
and I want to bind this do a CheckBoxList.DataSource
(in case that makes a difference).
Hows the most efficient way to do this?
I can think of two algorithms:
var data = HashSet<Enum> hashSet = new HashSet<Enum>(xs.Select(s => s.y));
chkBoxList.DataSource = data;
Or
var data = xs.Select(s => s.y).Distinct();
chkBoxList.DataSource = data;
My gut feeling is the HashSet but I'm not 100% sure.
Open to better ideas if anyone has any idea?
One way to get distinct values from an array of JavaScript objects is to use the array's map method to get an array with the values of a property in each object. Then we can remove the duplicate values with the Set constructor. And then we can convert the set back to an array with the spread operator.
Let's see how to get unique values from ArrayList. Convert ArrayList to HashSet to insert duplicate values in ArrayList but on the other hand, HashSet is not allowing to insert any duplicate value. While converting ArrayList to HashSet all the duplicate values are removed and as a result, unique values are obtained.
To get distinct values, the distinct() method is an intermediate operation that also filters the stream to pass the next operation. Java Stream collect() is used to collect the stream elements to a collection (in this case a list). Return type: Stream is an interface and the function.
Set data structure is used to store unique values only, meaning no duplicate values would be stored in a set. When a HashSet is created, it internally implements a HashMap. An element can be inserted into the HashSet using the 'add' function.
If it is a one time operation - use .Distinct
. If you are going to add elements again and again - use HashSet
The HashSet
one, since it keeps the objects around after the hashset object has been constructed, and foreach-ing it will not require expensive operations.
On the other hand, the Distinct
enumerator will likely be evaluated every time the DataSource is enumerated, and all the work of removing duplicate values will be repeated.
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