简体   繁体   中英

How to return a generic list collection in C#?

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}
public List<T> thisIsAtest<T>()
{
     return query;
}

You can't - period. You cannot use anonymous types outside their own scope, eg you cannot return them as return values from a method.

If you need to return them, you need to define a new concrete class instead of the anonymous type, and use that in the place of the anonymous type.

See Rick Strahl's blog post on the scoping of anonymous types, and see the MSDN docs here which clearly state:

An anonymous type has method scope. To pass an anonymous type, or a collection that contains anonymous types, outside a method boundary, you must first cast the type to object. However, this defeats the strong typing of the anonymous type. If you must store your query results or pass them outside the method boundary, consider using an ordinary named struct or class instead of an anonymous type.

OK, sure - there are dirty awful hacks to indeed return anonymous types. But if Microsoft's MSDN AND Jon Skeet discourage that practice, then - just don't do it . By definition and intention, anonymous types are bound to the method they're defined in.

UPDATE for chobo2: I don't know what your datatypes are - just guessing - but assuming "prefix" is an int and "marks" is a decimal, you could define a new class:

public class ReturnValue
{
    int prefix { get; set; }
    decimal Marks { get; set; } 
}  

and then your code would be a method that returns a List<ReturnValue> :

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

The key here is: in your .Select method, instead of creating a new instance of an anonymous type:

     .Select(group => new { prefix = group.Key, marks = .... }

you create an instance of a concrete type:

     .Select(group => new ReturnValue { prefix = group.Key, marks = .... }

This way, you'll have a concrete class ReturnValue - name that anything you like - and then you can easily return a list of that type, and use that type elsewhere, too.

You want to return an anonymous type from a regular method? I'm quite sure you can with Reflection, but there would be no type safety and a whole host of other problems. Not to mention it looks weird from the calling codes perspective. You would basically have to return object I think.

You would be better use a class or struct and stuff the values in there.

Anonymous types are very limited, you can only use them in the scope of the method were they are declared.

You can pass them back as plain objects, but then you lose the type information. I have seen some solutions passing a anonymous type around; but they use reflection to retrieve the properties at a later point.

If you declare the generic list as a global variable, you don't need to use return. I used the return function in my code anyway simply because marc_s said i couldn't. lol

 public static class Globals
    {
        public static List<string> CurPart = new List<string>();
    }
    public List<string> MSQueryRead1DArray(string sql, string db)
    {
        return Globals.CurPart;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM