2013-06-13 146 views
2

这是我的代码匿名对象:查询选择和使用where子句

var tree = new 
{ 
    id = "0", 
    item = new List<object>() 
}; 

foreach() 
{ 
    tree.item.Add(new 
    { 
     id = my_id, 
     text = my_name, 
     parent = my_par 
    }); 
} 

不过,我想用下面的更换在foreach代码:

foreach() 
{ 
    tree.item.Where(x => x.id == 2).First().Add(new 
    { 
     id = my_id, 
     text = my_name, 
     parent = my_par 
    }); 
} 

如何做到这一点?我发现该类型不包含id的定义。

这里的问题是匿名类型。

我试着创建一个新的类,它有2个属性:id,文本和父类,并且语法工作,但树的定义是无效的。

所以这里的问题是如何查询匿名类型,而不需要添加一个代表匿名类型的新类。

+1

您的匿名类型没有方法'Add'并且它不能有方法(除从对象继承)。所以你不能在一些匿名对象上调用'Add'方法。你在做什么?你为什么试图使用匿名类型? –

回答

3

如果您想要在不创建新类的情况下执行此操作,则可以使用dynamic进行过滤。

tree.item.Where(x => ((dynamic)x).id == 2).First().... 

虽然这会给你一个匿名对象,而不是一个集合,所以你不能添加任何东西。

+0

对象不包含添加的定义。 –

+1

该对象的基础类型是不具有Add的匿名对象。所以不知道你想做什么。 – Magnus

1

一,这真的很丑。你应该想到为此宣布一个班级(你对此有一个纯粹主义者的低估);)

二,你正在做的事情是不可能的。想想看,在你的第一个循环中,当你做tree.item.Where(x => x.id == 2).First()时,你得到的是x,这是一个对象,而对象没有Add方法。当你做

var p = tree.item.Where(x => x.id == 2).First(); //even if that was compilable. 

您收到此

new 
{ 
    id = 2, 
    text = "", 
    parent = null 
} 

var tree = new 
{ 
    id = "0", 
    item = new List<object> 
    { 
     new 
     { 
      id = 2, 
      text = "", 
      parent = null 
     } 
    } 
}; 

现在:为了说明,采取这种例子。现在你怎么去Add的东西呢?它确实是一个没有方法的匿名类型。

我只能假设,但你可能想这一点:

var treeCollection = new 
{ 
    id = 0, 
    item = new List<object> // adding a sample value 
    { 
     new // a sample set 
     { 
      id = 2, 
      text = "", 
      parent = null // some object 
     } 
    } 
}.Yield(); // an example to make it a collection. I assume it should be a collection 

foreach (var tree in treeCollection) 
{ 
    if (tree.id == 0) 
     tree.item.Add(new 
     { 
      id = 1, 
      text = "", 
      parent = null 
     }); 
} 

public static IEnumerable<T> Yield<T>(this T item) 
{ 
    yield return item; 
} 

或者在同一行:

treeCollection.Where(x => x.id == 0).First().item.Add(new 
{ 
    id = 1, 
    text = "", 
    parent = null 
});