C# 如何将匿名类型转换为 Ttype?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/901512/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 22:54:56  来源:igfitidea点击:

How can I convert Anonymous type to Ttype?

c#

提问by Vikas

How can I use Cast() Extension method for above conversion?

如何使用 Cast() 扩展方法进行上述转换?

e.g.

例如

var aType = anonymousType;

IEnumreable<MyType> = aType.Cast();

Solved By

解决者

aType.Select(i => new MyType { } ).ToList();

采纳答案by Guffa

The only type that you can cast an anonymous type to is Object. If you want any other type, you have to create those objects from the data in the anonymously typed objects.

您可以将匿名类型强制转换为的唯一类型是Object. 如果您想要任何其他类型,则必须从匿名类型对象中的数据创建这些对象。

Example:

例子:

List<MyType> items = aType.Select(t => new MyType(t.Some, t.Other)).ToList();

You should consider to create the MyTypeobjects already when you get the data, instead of creating anonymously typed objects.

您应该考虑MyType在获取数据时已经创建对象,而不是创建匿名类型的对象。

回答by MiffTheFox

回答by Dario

Is aTypeis an IEnumerable<anonymous type>returned by e.g. a linq query?

难道aType是一个IEnumerable<anonymous type>由例如LINQ查询返回的?

You might want to use Select(which applies a transformation function to an element) insted of Castwhich just performs a cast.

您可能想要使用Select(将转换函数应用于元素) insted ,Cast其中只执行强制转换。

IEnumerable<MyType> = aCollection.Select(e => SomeExpressionWithE);

回答by Gerardo Contijoch

Here's an article that may help you. Although I think Guffa is right, you should create an instance of your class whenever you need them. Anonymous types are not meant to be used that way.

这是一篇可能对您有所帮助的文章。尽管我认为 Guffa 是对的,但您应该在需要时创建类的实例。匿名类型不应该以这种方式使用。

Here's the link: http://www.codeproject.com/KB/cs/castinganonymous.aspx

这是链接:http: //www.codeproject.com/KB/cs/castinganonymous.aspx