Home > other >  Iterate over a generic type<T>
Iterate over a generic type<T>

Time:01-24

I don't know if this can be possible, but I will try to explain myself the best way that I can. Thank you for your help.

I'm trying to fit these entity objects in an integration with a third-party.

My problem is, I have these 3 entity type from the third-party, ObjectType1, ObjectType2, ObjectType3 object classes, all of these have the same base, so, my idea in order to no repeat the code several times was to create a fuction that accepts one generic list and inside of it, try to cast to the object type that I want and used to save the information in my principal entity.

I don't know if this can be possible or what would you recommend me to do, because what I'm trying to do is not to repeat the code several times.

Thank you again.

        public static List<ItemsToSave> TestList<T>(List<T> listOfT)
        {

            var itemsToSave = new List<ItemsToSave>();

            foreach (var item in listOfT)
            {
                object obj = null;
 
                switch (listOfT)
                {
                    case List<ObjectType1>:
                        obj  = item as ObjectType1;
                        break;
                    case List<ObjectType2>:
                        obj = item as ObjectType2;
                        break;
                    case List<ObjectType3>:
                        obj = item as ObjectType2;
                        break;
                }

                var itemtosaveEntity = new ItemsToSave()
                {
                    FirstName = obj.FirstName,
                    MiddleName = obj.MiddleName,
                    LastName = obj.LastName,
                };

                itemsToSave.Add(itemtosaveEntity);

            }

            return itemsToSave;
        }

CodePudding user response:

Try this

var listOfT = new List<BaseType>();
List<ItemsToSave> itemsToSave = ConvertList(listOfT);

public static List<ItemsToSave> ConvertList<T>(List<T> listOfT) where T : BaseType
{
    return
        listOfT
            .Select(i => new ItemsToSave()
            {
                FirstName = i.FirstName,
                MiddleName = i.MiddleName,
                LastName = i.LastName,
            })
            .ToList();
}

CodePudding user response:

You can define your generic function like this:

public static List<ItemsToSave> TestList<T>(List<T> listOfT) where t : BaseClass

This is is called a 'Where generic constraint', read more Here

That way the type you have in your function will be BaseClass and you can access all properties defined in that class.

  •  Tags:  
  • Related