Anyname Donotcare
Anyname Donotcare

Reputation: 11403

How to convert anonymous type to IListSource, IEnumerable, or IDataSource

I create the following anonymous type:

  int group_id = 0;
  int dep_code = 0;
  int dep_year = 0;
  string dep_name = string.Empty;
  int boss_num = 0;
  string boss_name = string.Empty;
  var list =  new  { group_id = group_id, dep_code = dep_code, dep_year = dep_year, dep_name = dep_name, boss_num = boss_num, boss_name = boss_name };

How to convert to IListSource, IEnumerable, or IDataSource. ??

Upvotes: 0

Views: 3034

Answers (2)

Matías Fidemraizer
Matías Fidemraizer

Reputation: 64943


Note

Based on some original poster's comment in my question, the question is about .NET Framework 3.5. I've re-tagged the question myself. Anyways, I leave this answer here because it may be useful in the future for the original poster and also for future visitors.


Instead of using an anonymous object, why don't you use an ExpandoObject?

dynamic list = new ExpandoObject();
list.group_id = group_id;
list.dep_code = dep_code;
// ... and so on.

A great detail is ExpandoObject implements IDictionary<string, object>, and bingo: IDictionary<string, object> will have a Values property, which implements IEnumerable<T>!

IEnumerable<object> items = ((IDictionary<string, object>)list).Values;

Update

Since I see Jon Skeet's answer was the right one for you, I guess you were looking for a list of anonymous objects rather than an anonymous object turned into "enumerable" (it's not that easy to know what was good for you from your question... I'm not going to delete my answer so any other visitor looking for something like my first understanding could still find my answer very useful).

Now, understanding your question better, you could do this also:

// Create a list of objects and you got it!
List<object> list = new List<object>();
list.Add(new { group_id, dep_code, dep_year, dep_name, boss_num, boss_name });

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1502076

If you're just looking to create a sequence with a single value, you can use an implicitly typed array:

int group_id = 0;
int dep_code = 0;
int dep_year = 0;
string dep_name = string.Empty;
int boss_num = 0;
string boss_name = string.Empty;
var list =  new[] { 
    new { group_id, dep_code, dep_year, dep_name, boss_num, boss_name }
};

Note that this uses projection initializers where the property name is inferred from the expression.

I'd strongly encourage you to use conventional names for your variables though, such as groupId. Also it's not clear what dep means here - if that's an abbreviation, you may want to expand it for clarity.

Upvotes: 3

Related Questions