Richard77
Richard77

Reputation: 21661

How to pass a list of anonymous object?

I've pushed most of a method functionality inside a store procedure. I'm returning a join result of 2 tables, so there is no type to collect the return data. I'm thinking of using anonymous type.

public static List<Anonymous Type> 
              SaveUsersToGroup(int groupId, List<int> userIds)
{


   //more here ...

   var list = new List<Anonymous Type>();
   foreach (DataRow row in dt.Rows)
   {

      list.Add(new { Id = row["Id"].ToString(), 
                     FirstName = row["FirstName"].ToString(),
                     LastName = row["LastName"].ToString()
              });
   }
}

Now how to create a list of anonymous object. And (most importantly) what will be the return type for this method?

Thanks for helping.

Upvotes: 0

Views: 241

Answers (3)

Konstantin
Konstantin

Reputation: 3294

you can use dynamic, since your projection is ananymous

Upvotes: 1

Jeroen Vannevel
Jeroen Vannevel

Reputation: 44448

The entire point about anonymous types is that they're anonymous. You're trying to name them, which doesn't make them anonymous anymore.

Either use dynamic (not my favorite solution) or create a class that holds Id, FirstName and lastName.

Upvotes: 3

MarcinJuraszek
MarcinJuraszek

Reputation: 125660

You can't do that:

You cannot declare a field, a property, an event, or the return type of a method as having an anonymous type.

Anonymous Types (C# Programming Guide)

You can declare mathod as IEnumerable<object> but you'll looks type safety going this way and you'll have* to use dynamic to read the results.

You should create simple POCO class and return set of that class items instead of anonymous type.

Upvotes: 1

Related Questions