How do I cast a List effectively?

前端 未结 8 1387
暖寄归人
暖寄归人 2020-12-08 15:09

I have a

List 

but I need a

List  

Is there a way to cast this in c

相关标签:
8条回答
  • 2020-12-08 15:50

    Since the list is coming from

    List<InputField> list = (from i .... select i).ToList();
    

    Couldn't you just fix the "select i" part to instead return IDataField instead? Something like this:

    List<InputField> list = (from i .... select (IDataField)i).ToList();
    

    If that doesn't work, perhaps the "Cast" extension to IEnumerable will work:

    List<DataField> list2 = list.Cast<IDataField>();
    
    0 讨论(0)
  • 2020-12-08 15:50

    I have the following string

     var str = "2 4 7 8 10";
    

    when I cast as follow

    var numbersInt2 = numbers.Split(' ')
                    .ToList().Cast<int>().ToList();
    

    it returns an exception but

    System.InvalidCastException: 'Specified cast is not valid.'

    , if using the following

    var numbersInt = numbers.Split(' ')
                    .ToList().ConvertAll(int.Parse);
    

    it works.

    0 讨论(0)
提交回复
热议问题