简体   繁体   English

Linq查询以基于ILookup获取DataContext实体

[英]Linq Query to get DataContext Entities based on ILookup

If I have an IEnumerable<int> Values , I can write a Linq to Entities query, like so: 如果我具有IEnumerable<int> Values ,则可以编写一个Linq to Entities查询,如下所示:

DataContext.Answers.Where(a => a.Organization == CurrentUser.Organization ||
    Values.Contains(a.QuestionId))

The (Values.Contains(a.QuestionId)) part is what my question concerns. (Values.Contains(a.QuestionId))部分是我的问题所关心的。

If Values were implemented instead as: ILookup<string, IEnumerable<int>>Values , how could I rewrite the query to get Answers where Values contains the key( a.Organization ) and the IEnumerable values for that key contains a.QuestionId ? 如果将Values实现为: ILookup<string, IEnumerable<int>>Values ,我如何重写查询以获取Answers ,其中Values包含键( a.Organization ),而该键的IEnumerable值包含a.QuestionId

First you'll need to flatten the ILookup<string, IEnumerable<int>> into an IEnumerable of some item that has both the organization and the question Id. 首先,您需要将ILookup<string, IEnumerable<int>>展平为具有组织和问题ID的某个项目的IEnumerable You'll need to get all of the groups in the lookup, get all of the collections of ids from the group, and then get all of the ids in that collection, and transform each of them into an object holding both that ID and the group's key. 您需要获取查找中的所有组,从该组中获取所有ID集合,然后获取该集合中的所有ID,然后将每个ID转换为一个既包含ID又包含ID组的密钥。 You can then use Contains on that collection to see if the answer's organization and question ID are in that collection of pairings. 然后,您可以在该集合上使用“ Contains ”,以查看答案的组织和问题ID是否在配对中。 By doing this you allow the collection to be translated into an IN clause in SQL. 通过这样做,您可以将集合转换为SQL中的IN子句。 Of course, if the lookup is particularly large, then that will be a problem; 当然,如果查找特别大,那将是一个问题; if it's small, it won't be. 如果很小,就不会。

You would do that like so: 您将这样做:

var flattenedValues = (from grouping in Values
                        from ids in grouping
                        from id in ids
                        select new
                        {
                            Organization = grouping.Key,
                            QuestionId = id,
                        })
                        .ToList();
DataContext.Answers.Where(a => a.Organization == CurrentUser.Organization ||
    flattenedValues.Contains(new
                        {
                            Organization = a.Organization,
                            QuestionId = a.QuestionId,
                        }));

If the lookup is particularly big, you may have no other choice but to pull all of the data from the table into memory and filter it by looking through the lookup on the application's side, or upload the data in that lookup into a temporary table in the list. 如果查找特别大,您可能别无选择,只能将表中的所有数据拉到内存中,并通过在应用程序一侧进行查找来对其进行过滤,或者将该查找中的数据上载到临时表中。名单。

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

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