简体   繁体   中英

LINQ get collection in anonymous type

i have the following LINQ statement:

var query =(from item in _itemRepository.FindAll()
            where item.Id == "20649458"
                from singelitem in item.ListOfChildren
                where singelitem.Property == "singelitem"
                from manyitems in item.ListOfChildren
                where manyitems.Property == "many"
                select new
                            {
                                item.Id,
                                singelitem,
                                manyitems 
                            });
var result = query.ToList();

Tasks is a collection of objects and the where clause tasks.Property == "something" matches several items in the collection, but when i use a anonymous type in the select, i only get back one item (the first) of the matching results instead of a collection of Tasks. How can i get back all the matching tasks in a collection?

Edit: What really happends is that i get flat objects, (just like a db result set from a join statement).

When you don't use anonymous type you're dealing with entity class which lazy loads the tasks when you access them. If you want to load tasks with your results try using Include method to eager load children. See How do you construct a LINQ to Entities query to load child objects directly, instead of calling a Reference property or Load()

This is the proper behavior of Linq. In fact what you are expecting is not possible. You are expecting a single item matching item.Id == "123"; and what if more than one? it just creates an anonymous item for each matched item. Just think of changing the first "from" statement with the second one; what would you expect?

Also, there is no relationship between first "from" statement and the second one which makes this query a bit "strange". Why not just splitting the query into 2; and creating a new object with the desired properties?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM