I create a list with multiple DynamicNode items. When I try to get the distinct items in the list, it doesn't remove the double items, I just get the same list...
Is this a bug or a feature?
e.g.
List<DynamicNode> myList = new List<DynamicNode>();
myList.Add( new DynamicNode( 1 ) ); myList.Add( new DynamicNode( 2 ) ); myList.Add( new DynamicNode( 2 ) ); myList.Add( new DynamicNode( 1 ) ); myList.Add( new DynamicNode( 3 ) );
myList = myList.Distinct().ToList();
Result: the list still contains the 5 items myList.Count --> 5
What version of Umbraco are you using? In the newer version there are some useful extension methods. If you add the Umbraco.Core namespace you'll be able to do this:
I think it must be version 6.0.5 or maybe even newer.
I think I tried the Distinct( x => x.Id ) but it was not working.
I changed the code to use a List<int> with the node id's, so I got it working that way. When I need something similar again I will retry your other solutions :)
Get Distinct() on a List<DynamicNode>
Hey.
I create a list with multiple DynamicNode items.
When I try to get the distinct items in the list, it doesn't remove the double items, I just get the same list...
Is this a bug or a feature?
e.g.
List<DynamicNode> myList = new List<DynamicNode>();
myList.Add( new DynamicNode( 1 ) );
myList.Add( new DynamicNode( 2 ) );
myList.Add( new DynamicNode( 2 ) );
myList.Add( new DynamicNode( 1 ) );
myList.Add( new DynamicNode( 3 ) );
myList = myList.Distinct().ToList();
Result: the list still contains the 5 items
myList.Count --> 5
Thank you.
K.
A DynamicNode is a reference type. Reference types aren't equal unless you've overridden object.Equals() or it's the same instance.
In your example, the instances at index 0 and 3 are different instances, and hence not equal.
Distinct can however use a custom equality comparer.
Have a look here:
http://msdn.microsoft.com/en-us/library/bb338049.aspx (plain static comparer for a given case)
and here:
http://stackoverflow.com/questions/1071609/iequalitycomparer-for-anonymous-type (utility comparer where you specify a lambda for your current need)
how about this! first check if the item is not in your list then add it like below:
What version of Umbraco are you using? In the newer version there are some useful extension methods. If you add the Umbraco.Core namespace you'll be able to do this:
Jeroen
I think it must be version 6.0.5 or maybe even newer.
I think I tried the Distinct( x => x.Id ) but it was not working.
I changed the code to use a List<int> with the node id's, so I got it working that way.
When I need something similar again I will retry your other solutions :)
Thank you.
Kris.
Note that @Jeroen showed a method called DistinctBy, not Distinct. It's a custom extension in umbraco, not the BCL.
is working on a reply...