开发者

How to return IList<T>

following function return List of records

 public IList<T> GetAll()
 {
   return db.TabMasters.ToList<T>();
 }

Error: 'System.Data.Objects.ObjectSet' does not contain a definition for 'ToList' and the best extension method overload 'System.Linq.Enumerable.ToList(System.Collections.开发者_如何学JAVAGeneric.IEnumerable)' has some invalid arguments


I imagine TabMasters is a strongly typed collection and therefore cannot return a list of a generic type. Have you tried db.TabMasters.ToList() instead?


The correct syntax is:

db.TabMasters.Cast<T>().ToList()

Documentation:

  • IEnumerable<TResult> Enumerable.Cast<TResult>(this IEnumerable source)
  • List<TSource> Enumerable.ToList<TSource>(this IEnumerable<TSource> source)

If you don't want to use the LINQ extension, List<T> has a public constructor that accepts a single IEnumerable<T> argument


IList<T> is the Interface that is used by List<T> and several other similar containers. You can't return an Interface itself - you have to return an object that implements IList<T>. Though I don't know exactly what your situation is, the best choice is most likely List<T>.

Also, you have a problem with the generic Type T. If you want the method to be generic, then you have to cast all the values in db.TabMasters to Type T. This gets tricky because you'll have to limit the possible Types used for T to prevent Exceptions caused by an invalid cast (see here). If you only need to return one type, then you should define that as the return type instead of using T. For example, lets say that all the values in db.TabMasters are string. Then you'd use:

public IList<string> GetAll()
{
    return db.TabMasters.ToList();
}

If you really need the method to be generic, then you have to cast the values in db.TabMasters to the type you want to return:

public IList<T> GetAll<T>()
{
    return db.TabMasters.Cast<T>().ToList();
}

Note that if the object type stored in db.TabMasters can't be cast to T, the method will throw an InvalidCastException.

Happy Coding!


have you looked here http://msdn.microsoft.com/en-us/library/dd412719.aspx

there appears to be a couple of methods that may be of use AsEnumerable and GetList seem like possibilities

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜