简体   繁体   English

LINQ以匿名类型获取集合

[英]LINQ get collection in anonymous type

i have the following LINQ statement: 我有以下LINQ语句:

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. Tasks是对象的集合,而where子句 tasks.Property == "something"匹配集合中的多个项目,但是当我在select中使用匿名类型时,我只会取回匹配结果中的一个(第一个)而不是任务的集合。 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). 编辑:真正发生的是我得到了平面对象(就像从join语句得到的数据库结果集一样)。

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. 如果您想用结果加载任务,请尝试使用Include方法来渴望加载子级。 See How do you construct a LINQ to Entities query to load child objects directly, instead of calling a Reference property or Load() 请参见如何构造LINQ to Entities查询以直接加载子对象,而不是调用Reference属性或Load()

This is the proper behavior of Linq. 这是Linq的正确行为。 In fact what you are expecting is not possible. 实际上,您所期望的是不可能的。 You are expecting a single item matching item.Id == "123"; 您需要一个与item.Id相匹配的项目。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; 只需考虑将第一个“ from”语句更改为第二个; what would you expect? 您会期望什么?

Also, there is no relationship between first "from" statement and the second one which makes this query a bit "strange". 同样,第一个“ from”语句和第二个“ from”语句之间没有任何关系,这使得此查询有点“奇怪”。 Why not just splitting the query into 2; 为什么不将查询分为2个; and creating a new object with the desired properties? 并创建具有所需属性的新对象?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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