简体   繁体   中英

How to check a list for a different instance of a class inheriting generic interface

I have a List<ICar<T>> cars. I want to add new ICar<T> Honda to the list only if it does not already exist in there. The structure is like:

class Honda : IHonda{}
interface IHonda : ICar<T>

class Ford  : IFord{}
interface IFord  : ICar<T>

I only want to put one of each type of car into the list, but only knowing that they are ICar<T> . I don't know ahead of time the list of possible cars. How can this be done?

I was thinking something like

cars.Any(i => i.GetType().GetInterfaces().Contains(
                    car
                    .GetType()
                    .GetInterfaces()
                    .Where(s =>!cars.GetType().GenericTypeArguments != s.GenericTypeArguments
))))

However, something is wrong with that and I can't quite see a path through this one.

If you have a Type instance corresponding to T then you can use:

Type t = //
Type carType = typeof(ICar<>).MakeGenericType(t);
bool exists = cars.Any(c => carType.IsAssignableFrom(c.GetType()));

I think that you can use

 //get list of all interfaces in the currrent car list
 //you will have to check the contents of yourList as it may contain some types 
 //such as IList / IEnumerable that you will want to filter out.
 var yourList =  list.SelectMany(car => car.GetType().GetInterfaces());

 //check get all interfaces on your car and check if the list contains it
 bool exists = yourCar.GetType().GetInterfaces().Any(c => yourList.Contains(c));

You may be able to compare the elements using the fully qualified name of the type.

CarTypeComparer compareCarTypes = new CarTypeComparer();

if (!List.contains(car, compareCarTypes))
{
   // insert car into list
}

class CarTypeComparer : IEqualityComparer<ICar<T>>
{
   public bool Equals(ICar<T> car1, ICar<T> car2)
   {
      if (car1.GetType().FullName == car2.GetType().Fullname)
      {
          return true;
      }
      else 
      {
          return false;
      }

   }
   // implement GetHashCode() ....
}

Add a CarModel property inside of your ICar interface,and then implement it in your classes.For example in Honda class:

public string CarModel { get { return "Honda"; } }

you can check CarModel property in your query and ofcourse you can group your cars by CarModel,i hope this helps..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM