简体   繁体   中英

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. ??

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.


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 });

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