1
\$\begingroup\$

I have the following code:

public abstract class BaseViewModel<PrimaryKey, ModelType>
{
    //Some base fields

    public static List<T> Convert<T>(IEnumerable<ModelType> collection) 
        where T : BaseViewModel<PrimaryKey, ModelType>, new()
    {
        var list = new List<T>();

        if (collection != null)
        {
            foreach (var item in collection)
            {
                var view = new T();
                view.Value = item;

                list.Add(view);
            }
        }

        return list;
    }
}

Of course, it works because it requires to I set a generic type.

var list = GroupViewModel.Convert<GroupViewModel>(model);

There is GroupViewModel extends from BaseViewModel. But how can I reduce this generic casting to it will get GroupViewModel type automaticaly when I call it so: var list = GroupViewModel.Convert(model);. Is it possible? Just I learn C# only.

\$\endgroup\$
4
\$\begingroup\$

I don't know what to say more then:

  • make it an extension and return an IEnumerable<T> instead by using linq

do you mean something like this?

public static IEnumerable<T> Convert<T>(this IEnumerable<ModelType> modelTypes) 
    where T : BaseViewModel<PrimaryKey, ModelType>, new()
{
    return modelTypes.Select(x => new T { Value = x });    
}

use it:

var groupViewModels = modelTypes.Convert<GroupViewModel>().ToList();
| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ It isn't that I wanted =) But I like this solution! Thank you very much! \$\endgroup\$ – Шах Oct 14 '16 at 8:50
  • \$\begingroup\$ Sorry, but your solution doesn't work! Although, I can't understand why C# can't get generic type in this expression. \$\endgroup\$ – Шах Oct 24 '16 at 11:54
  • \$\begingroup\$ @Шах with just doesn't work we won't get any further... \$\endgroup\$ – t3chb0t Oct 24 '16 at 12:27
  • \$\begingroup\$ "Although, I can't understand why C# can't get generic type in this expression." \$\endgroup\$ – Шах Oct 24 '16 at 12:29

Not the answer you're looking for? Browse other questions tagged or ask your own question.