我的代码收到由另一种方法创建的匿名对象。我想访问并遍历此对象中的嵌套集合。我试图提出几种不同的方法来使用'as'关键字进行转换,但无济于事。
这里是创建对象的代码:
var result = new object();
foreach (var item in items)
{
result = new
{
Variants = item.Value.Select(m => m.Item2).GroupBy(n => n.Item1).Select(r => new
{
Name = r.Key,
Items = r.Select(p => new
{
Value = p.Item2.Trim(),
Text = p.Item2.Substring(0, p.Item2.LastIndexOf('_')).Trim()
}).Where(p => !string.IsNullOrEmpty(p.Text)).ToList()
})
};
}
当我将鼠标悬停在接收此匿名类型的变量上时,Visual Studio给我以下签名:
{ Variants = {System.Linq.Enumerable.WhereSelectEnumerableIterator<System.Linq.IGrouping<string, System.Tuple<string, string>>, <>f__AnonymousType1<string, System.Collections.Generic.List<<>f__AnonymousType2<string, string>>>>} }
简而言之:我想访问集合的Text字段。
这是QuickWatch窗口,显示此对象的结构和数据:QuickWatch Window
非常感谢您的帮助!
PS:无法更改发送方法中的代码。
如果没有静态类型的类,则不能将其强制转换为它。对于具有类型的匿名类型,意味着您可以在方法中将其本地放置,也可以将其作为泛型方法的参数获取-此处不是这种情况。
您的选择实际上仅限于某种反思以深入研究匿名类。最简单的方法是通过像dynamic
这样的((dynamic)myVariable).Text
来让运行时处理反射。