petko_stankoski
petko_stankoski

Reputation: 10723

Query for selecting and anonymous object with where clause

This is my code:

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

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

But I want to replace the code in the foreach with the following:

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

How to do this? I get exception that the type doesn't contain a definition for id.

The problem here is the anonymous type.

I tried creating a new class which would have 2 properties: id, text and parent and the syntax worked, but the tree's definition was invalid.

So the question here is how to make a query to an anonymous type, without adding a new class which would represent the anonymous type.

Upvotes: 2

Views: 1495

Answers (2)

Magnus
Magnus

Reputation: 46997

If you want to do it without creating a new class you can use dynamic for the filtering.

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

Although that will give you a single anonymous object and not a collection so you can not add anything to it.

Upvotes: 3

nawfal
nawfal

Reputation: 73311

One, this is really ugly. You should think of declaring a class for this (you got a downvote from some purist for this I assume ;))

Two, you're doing something that's impossible. Think about this, in your first loop, when you do tree.item.Where(x => x.id == 2).First(), you're getting x back, which is an object and object doesn't have an Add method. To illustrate, take this example:

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

Now when you do

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

you are getting this

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

back. Now how are you going to Add something to that? It really is an anonymous type with no method on it.

I can only assume, but you might want this:

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

Or in one line:

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

Upvotes: 1

Related Questions