2

这是我的代码:

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、text 和 parent,并且语法有效,但树的定义无效。

所以这里的问题是如何在不添加代表匿名类型的新类的情况下对匿名类型进行查询。

4

2 回答 2

3

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

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

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

于 2013-06-13T11:07:51.117 回答
1

一,这真的很丑。你应该考虑为此声明一个类(我认为你得到了一些纯粹主义者的反对票;))

第二,你正在做一些不可能的事情。想一想,在你的第一个循环中,当你这样做时tree.item.Where(x => x.id == 2).First(),你会x回来,这是一个对象,而对象没有Add方法。为了说明,举这个例子:

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

现在当你做

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

你得到这个

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
});
于 2013-06-13T11:57:12.107 回答