简体   繁体   English

在列表中添加值<ienumerable<t> &gt; 内部 foreach </ienumerable<t>

[英]Adding values in List<IEnumerable<T>> inside foreach

what I want to do is to add for example class in IEnumerable after specific check我想要做的是在特定检查后在 IEnumerable 中添加例如 class

public static IEnumerable<T> GroupBy<T, O> (this IEnumerable<T> list, Func<T, O> filter)
    {
        List<IEnumerable<T>> grouped = new List<IEnumerable<T>>();

        foreach (var item in list)
        {
            foreach (var g in grouped)
            {
                foreach (var p in g)
                {
                    if (filter(p).Equals(filter(item)))
                    {
                        // Add item to g
                    }
                }
            }
        }
    }

Is something like this possible in foreach?在foreach中是否可能发生这样的事情?

No, that's not possible: every time you change source collection, foreach has to be started anew.不,这是不可能的:每次更改源集合时,都必须重新启动foreach You'll need to have a separate collection for intermediate accumulation, then join that collection with grouped .您需要有一个单独的集合来进行中间累积,然后将该集合与grouped一起加入。

Also, your algorithms doesn't work correctly: the second foreach will never start working as on the first iteration there will be no items in grouped collection.此外,您的算法无法正常工作:第二个foreach永远不会开始工作,因为在第一次迭代时, grouped集合中不会有任何项目。 So you will just iterate list without applying any logic to its elements.因此,您将只迭代list而不对其元素应用任何逻辑。

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

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