简体   繁体   中英

Genieric convert List of string to list of enum

Is it possible make a generic method where I don't know what type of enum I have and parsing string to this type?

Example:

I want make mapper from some model with list of string to model with list of enums

model 1

public class Model1 {
    public List<string> SomeList1 {get; set;}
    public List<string> SomeList2 {get; set;}
}

model 2

public class Model2{
   public List<MyEnum1> SomeList1 {get; set;}
   public List<MyEnum2> SomeList2 {get; set;}
}

Now I would like parsing Model1.SomeList1 to Model2.SomeList1 and Model1.SomeList2 to Model2.SomeList2 in one generic method.

Is it at all possible? If yes, how I can make it?

You can change your classes like below.

class Program
{
    static void Main(string[] args)
    {
        Model m = new Model();
        m.SomeList1=new List<baseModel>();
        var _string = m.SomeList1.First<baseModel>().sVal;
        var _enum = m.SomeList1.First<baseModel>().eMyEnum;
    }
}


class baseModel {
    public string sVal;
    public myEnum eMyEnum;
    public string sVal2;
    public myEnum eMyEnum;
}

class Model
{
    public List<baseModel> SomeList1 { get; set; }

}

        enum myEnum{
        someVal=1,
        someVal2=2
    }

Thenk You for reply!

In a broader context, I have databases and I have one model to tables in this db and one model to db for my web page (web has its own database and the model with other data). Now I wont mapping values this two modles.

User in web page has drobdown (enum) and db is string. I have a few similar situations.

I think this will fit your needs:

  public static List<T> ConvertToEnumList<T>(this List<string> statusList) where T : struct, IConvertible
    {
        var list = new List<T>();
        statusList.ForEach(status =>
        {
            if (Enum.TryParse<T>(status, out var e))
            {
                list.Add(e);
            }
        });
        return list;
    }

this does filter out all non-parseable enums, you may want to throw an error if that is needed.

You can use at like this:

new List<string>{"string1", "string2"}.ConvertToEnumList<EnumType>()

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