Cast IList to List

后端 未结 9 1675
时光取名叫无心
时光取名叫无心 2020-12-08 06:09

I am trying to cast IList type to List type but I am getting error every time.

List subProducts= Model.subproduct         


        
相关标签:
9条回答
  • 2020-12-08 06:35

    The other answers all recommend to use AddRange with an IList.

    A more elegant solution that avoids the casting is to implement an extension to IList to do the job.

    In VB.NET:

    <Extension()>
    Public Sub AddRange(Of T)(ByRef Exttype As IList(Of T), ElementsToAdd As IEnumerable(Of T))
       For Each ele In ElementsToAdd
          Exttype.Add(ele)
       Next
    End Sub
    
    

    And in C#:

    public void AddRange<T>(this ref IList<T> Exttype, IEnumerable<T> ElementsToAdd)
    {
        foreach (var ele in ElementsToAdd)
        {
            Exttype.Add(ele);
        }
    }
    
    0 讨论(0)
  • 2020-12-08 06:40

    Try

    List<SubProduct> subProducts = new List<SubProduct>(Model.subproduct);
    

    or

    List<SubProduct> subProducts = Model.subproducts as List<SubProduct>;
    
    0 讨论(0)
  • 2020-12-08 06:42
    List<SubProduct> subProducts= (List<SubProduct>)Model.subproduct;
    

    The implicit conversion failes because List<> implements IList, not viceversa. So you can say IList<T> foo = new List<T>(), but not List<T> foo = (some IList-returning method or property).

    0 讨论(0)
  • 2020-12-08 06:42

    This is the best option to cast/convert list of generic object to list of string.

    object valueList;
    List<string> list = ((IList)valueList).Cast<object>().Select(o => o.ToString()).ToList();
    
    0 讨论(0)
  • 2020-12-08 06:45

    How about this:

    List<SubProduct> subProducts = Model.subproduct.ToList();
    
    0 讨论(0)
  • 2020-12-08 06:47

    In my case I had to do this, because none of the suggested solutions were available:

    List<SubProduct> subProducts = Model.subproduct.Cast<SubProduct>().ToList();
    
    0 讨论(0)
提交回复
热议问题