简体   繁体   English

如何编写此linq内部查询?

[英]How do I write this linq inner query?

I want to write a linq query where I want to check each iteration of an inner list. 我想编写一个linq查询,其中要检查内部列表的每次迭代。 Without linq, this would basically be a nested for loop - like this: 没有linq,这基本上是嵌套的for循环-像这样:

List<Item> selectedList = new List<Item>();
            foreach (Item i in item.Children)
            {
                var childPages = ((from innerItem in i.Children
                                   where innerItem.Template.BaseTemplates.Contains(new TemplateItem(ContextDatabase.GetItem(templateID)), new Compare())
                                   select innerItem).DefaultIfEmpty());

                if (childPages.First() == null)
                {
                    selectedList.AddRange(childPages.ToList());
                }
            }

I converted the inner loop into a linq query - now I want to convert the for loop into the same - is there a way to write this in linq, so that I don't have to have the foeach loop? 我将内部循环转换为linq查询-现在我想将for循环转换为相同的查询-有没有办法在linq中编写此代码,这样就不必使用foeach循环了?

I can't see your classes, so this is a best guess. 我看不到您的课程,所以这是最好的猜测。 Also, I'm assuming you don't have to create a new instance of TemplateItem and Compare repeatedly inside the LINQ statement. 另外,我假设您不必在LINQ语句中创建TemplateItem的新实例并重复Compare

var templateItem = new TemplateItem(ContextDatabase.GetItem(templateID));
var comparer = new Compare();

selectedList.AddRange(item.Children.SelectMany(
    x => x.Children.Where(y => y.Template.BaseTemplates.Contains(templateItem, comparer))));

(I'm using the method syntax here instead of query syntax, since that's what I'm more familiar with. The results should be the same.) (我在这里使用方法语法而不是查询语法,因为这是我更熟悉的方法。结果应该是相同的。)

It looks like you're getting an item from the database on each iteration in order to do a comparison ... is that what you absolutely require? 看起来您每次迭代都从数据库中获取一个项目以便进行比较...这是您绝对需要的吗? There should be an easier way to do the comparisons based on just id's (but would need more information from you I think). 应该有一种更简单的方法来根据ID进行比较(但我想需要您提供更多信息)。

Anyway, to remove the outer foreach , you can do another from clause: 无论如何,要删除外部的foreach ,您可以执行另一个from子句:

var childPages = (from i in item.Children
                 from innerItem in i.Children
                 where innerItem.Template.BaseTemplates.Contains(new TemplateItem(ContextDatabase.GetItem(templateID)), new Compare())
                 select innerItem).DefaultIfEmpty();

But again, I'd look closely at the need for ContextDatabase.GetItem(templateID) 但是再次,我将仔细研究对ContextDatabase.GetItem(templateID)

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

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