Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot implicity convert type System.Collections.Generic.IEnumerable<B> to System.Collections.Generic.List<B>

With the code below i get this error and need help with how to let method Load return List<B>

Cannot implicity convert type System.Collections.Generic.IEnumerable to System.Collections.Generic.List

public class A
    {
      public List<B> Load(Collection coll)
      {
        List<B> list = from x in coll select new B {Prop1 = x.title, Prop2 = x.dept};
        return list;
      }
    }

public class B
{
  public string Prop1 {get;set;}
  public string Prop2 {get;set;} 
}
like image 930
Andy Avatar asked Nov 21 '25 13:11

Andy


2 Answers

Your query returns an IEnumerable, while your method must return a List<B>.
You can convert the result of your query to a list via the ToList() extension method.

public class A
{
   public List<B> Load(Collection coll)
   {
       List<B> list = (from x in coll select new B {Prop1 = x.title, Prop2 = x.dept}).ToList();
       return list;
   }
}

The type of the list should be inferred automatically by the compiler. Were it not, you would need to call ToList<B>().

like image 93
Rotem Avatar answered Nov 23 '25 02:11

Rotem


You need to convert the enumeration to a list, there's an extension method to do that for you e.g. try this:

    var result = from x in coll select new B {Prop1 = x.title, Prop2 = x.dept};
    return result.ToList();
like image 27
Steve Avatar answered Nov 23 '25 01:11

Steve



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!