How to return a generic list collection in C#?

chobo2 picture chobo2 · Dec 20, 2009 · Viewed 38.6k times · Source

I have some linq to sql method and when it does the query it returns some anonymous type.

I want to return that anonymous type back to my service layer to do some logic and stuff on it.

I don't know how to return it though.

I thought I could do this

public List<T> thisIsAtest()
{
     return query;
}

but I get this error

Error   1   The type or namespace name 'T' could not be found (are you missing a using directive or an assembly reference?)

So not sure what assembly I am missing or if that is even the case.

Thanks

EDIT

Ok my first problem was solved but now I have a new problem that I am not sure how to fix since I don't know much about anonymous types.

I get this error

Cannot implicitly convert type 'System.Collections.Generic.List' to 'System.Collections.Generic.List

Here is the query

   DbContext.Table.Where(u => u.Table.UserId == userId && u.OutOFF != 0)
       .GroupBy(u => new { u.Table.Prefix })
       .Select(group => new { prefix = group.Key, 
                              Marks = group.Sum(item => (item.Mark * item.Weight) / item.OutOFF) })
       .ToList();

Edit 2

public class ReturnValue
{
   string prefix { get; set; }
   decimal? Marks { get; set; } 
}

public List<ReturnValue> MyTest(Guid userId)
{
   try
   {
       var result = dbContext.Table.Where(u => u.Table.UserId == userId && u.OutOFF != 0).GroupBy(u => new { u.Table.Prefix })
       .Select(group => new { prefix = group.Key, Marks = group.Sum(item => (item.Mark * item.Weight) / item.OutOFF) }).ToList();
       return result;
   }
   catch (SqlException)
   {
       throw;
   }

the select has this in it

Anonymous Types:

a is new{string Prefix}
b is new{ 'a prefix, decimal? marks}

Answer

Yuriy Faktorovich picture Yuriy Faktorovich · Dec 20, 2009
public List<T> thisIsAtest<T>()
{
     return query;
}