Home > database >  How can I populate a TreeViw with a List<object> and display properties without duplicates?
How can I populate a TreeViw with a List<object> and display properties without duplicates?

Time:12-03

I have an Entry class, with properties Building, Floor, Room, and Product. I receive a spreadsheet that gets turned into a List<Entry>, and here's a small example of what it looks like:

List<Entry> Entries.Add(new Entry("Building A", "Floor 4", "Room 6", "Printer"));
List<Entry> Entries.Add(new Entry("Building A", "Floor 4", "Room 6", "Computer Monitor"));
List<Entry> Entries.Add(new Entry("Building A", "Floor 5", "Room 8", "Office Desk"));
List<Entry> Entries.Add(new Entry("Building B", "Floor 2", "Room 8", "Printer"));
List<Entry> Entries.Add(new Entry("Building B", "Floor 2", "Room 12", "Office Chair"));

I would like to display this list of objects in a TreeView like so:

Building A
--Floor 4
----Room 6
------Printer
------Computer Monitor
--Floor 5
----Room 8
------Office Desk
Building B
--Floor 2
----Room 8
------Printer
----Room 12
------Office Chair

Notice how there are no duplicates in the TreeView: How Floor 4 Room 6 didn't appear twice even though it appeared two times in the List<Entry> Entries list. This is what I am trying to accomplish. I am not concerned with duplicates in my Entries list, as I will be using the TreeView to reference Entry later.

I've tried using a HierarchicalDataTemplate in many different ways and haven't had any luck. I've tried making Building, Floor, Room, and Product nested classes in Entry with no luck, and all the examples I see of HierarchicalDataTemplate use a class that contains another List<object> as a parameter, which is not what I have.

Thank you in advance!

CodePudding user response:

There are some collections in .NET that disallow duplicates. HashSet is one such collection, and I think SortedSet also prevents dupes (with the added overhead of sorting). There may be others. So, you could use such a collection to remove the dupes.

However, that may not work as expected if you do not also add equality members to your class or struct. See https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/statements-expressions-operators/how-to-define-value-equality-for-a-type

You could always write a function to remove the dupes, but you'll have to address "What constitutes a dupe?" - and that is the same question you'll be answering by creating the equality members (Equals and GetHashCode).

  • Related