vini
vini

Reputation: 4742

How to convert one generic list to another

public static List<IndianAppStore_GetAllAppsByLanguage_ResultCache> GetAllApps(bool initialized, string language)
{
    List<IndianAppStore_GetAllAppsByLanguage_ResultCache> objApp = new List<IndianAppStore_GetAllAppsByLanguage_ResultCache>();

    List<IndianAppStore_GetAllAppsByLanguage_Result> objApps = new List<IndianAppStore_GetAllAppsByLanguage_Result>();

    if (initialized == false)
    {
        var t = ListCopy(objApps, x => (IndianAppStore_GetAllAppsByLanguage_ResultCache)x); // Error
        objApp = admin.getAllAppsByLanguage(language).ToList();
    }
    else
    {
    }
}

public static List<TResult> ListCopy<TSource, TResult>(List<TSource> input, Func<TSource, TResult> convertFunction)
{
    return input.Select(x => convertFunction(x)).ToList();
}

My Class

public class IndianAppStore_GetAllAppsByLanguage_ResultCache
{
    public long AppId { get; set; }
    public string AppName { get; set; }
    public string AppDisplayName { get; set; }
    public string AppDetails { get; set; }
    public string AppImageURL { get; set; }
    public byte[] AppImageData { get; set; }
    public long CategoryId { get; set; }
    public Nullable<long> SubCategoryId { get; set; }
    public string AppCreatedBy { get; set; }
    public System.DateTime AppCreatedOn { get; set; }
    public string AppModifiedBy { get; set; }
    public Nullable<System.DateTime> AppModifiedOn { get; set; }
    public Nullable<bool> isDeleted { get; set; }
    public Nullable<bool> isPromotional { get; set; }
    public string GenderTarget { get; set; }
    public Nullable<long> CountryId { get; set; }
    public Nullable<long> StateId { get; set; }
    public Nullable<long> AgeLimitId { get; set; }
    public Nullable<int> AppMinAge { get; set; }
    public Nullable<int> AppMaxAge { get; set; }
}

enter image description here

I am trying to convert one generic class to another but getting this error

Upvotes: 0

Views: 681

Answers (1)

Martin Liversage
Martin Liversage

Reputation: 106886

IndianAppStore_GetAllAppsByLanguage_Result and IndianAppStore_GetAllAppsByLanguage_ResultCache are different types and you cannot cast the first type to the other as you are doing in this statement:

var t = ListCopy(objApps, x => (IndianAppStore_GetAllAppsByLanguage_ResultCache)x);

If the types have the same structure you should probably just have one instead of two types. Otherwise you will have to copy the data from the first type to the other. E.g.:

var t = ListCopy(objApps, x => new IndianAppStore_GetAllAppsByLanguage_ResultCache {
  AppId = x.AppId,
  AppName = x.AppName,
  ...
});

This becomes tedious very quickly and one option is to use a library like AutoMapper to automate the process.

Upvotes: 1

Related Questions