-1

What is the best way to make a data structure similar to HashSet but unique types instead of values.

How can I simplify this code, it seems to me that I'm doing something wrong and going through the whole list is unnecessary.

An example of what I have:

public abstract class Foo {}
public class FooA : Foo {}
public class FooB : Foo {}

public class FooList : List<Foo>
{
    public new void Add(Foo fooItem)
    {
        // как то без перебора
        foreach (var item in this)
        {
            if (item.GetType() == fooItem.GetType())
                return;
        }
        base.Add(fooItem);
    }
}

This is how it is used:

FooA fooA = new FooA();
FooB fooB = new FooB();
FooB anotherFooB = new FooB();

FooList list = new FooList();
list.Add(fooA);
list.Add(fooB);
list.Add(anotherFooB);

foreach(var item in list)
{
  Console.WriteLine(item);
}
/* Output:
FooA
FooB
*/
Be4Die
  • 33
  • 5
  • 1
    You could just use a `HashSet`? The point of a hashset is that it hashes its values for unicity, just so that it doesn't have to check all items but instead can check the bucket belonging to the hash-to-be-added. – CodeCaster May 29 '23 at 19:06
  • 2
    Maybe you want a `Dictionary`? – Wyck May 29 '23 at 19:07
  • 2
    Don't inherit from `List` or other collection types to create a collection of something in particular. https://stackoverflow.com/a/21694054/154766 – Asik May 29 '23 at 21:05
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community May 30 '23 at 07:14

1 Answers1

1

You can use HashSet<Type>, e.g.

using System;
using System.Collections;
using System.Collections.Generic;

...

public class FooList : IEnumerable<Type> {
  private HashSet<Type> m_Types = new HashSet<Type>();

  public bool Add(object value) => value is null
    ? false
    : m_Types.Add(value.GetType());

  public IEnumerator<Type> GetEnumerator() => m_Types.GetEnumerator();

  IEnumerator IEnumerable.GetEnumerator() => m_Types.GetEnumerator();
}

Then you can use your code:

FooA fooA = new FooA();
FooB fooB = new FooB();
FooB anotherFooB = new FooB();

FooList list = new FooList();
list.Add(fooA);
list.Add(fooB);
list.Add(anotherFooB);

foreach(var item in list)
{
  Console.WriteLine(item);
}

And get expected output:

FooA
FooB

Fiddle

Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215