Cannot implicitly convert List to Collection

后端 未结 7 2125
悲哀的现实
悲哀的现实 2020-12-08 13:44

This is a compiler error (slightly changed for readability).

This one always puzzled me. FxCop tells that this is a bad thing to return List and classes that are\\de

7条回答
  •  难免孤独
    2020-12-08 13:58

    This is how you convert from List to Collection (while using LINQ):

    The old function:

    public List GetEmployee(int id)
    {
         return ( from e in MyDataContext.Employees
                       select new Employee()
                       {
                         e.empId = id
                       }
                 ).ToList();
    }
    

    After conversion:

    using System.Collection.ObjectModel;
    
    public Collection GetEmployee(int id)
    {
               return new Collection( 
                   (from e in MyDataContext.Employees
                         select new Employee()
                         {
                           e.empId = id
                         }
                    ).ToList() as IList
               );
    }
    

提交回复
热议问题