LINQ C#复杂的嵌套结构 [英] LINQ C# complex nesting structure

查看:105
本文介绍了LINQ C#复杂的嵌套结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我设法从对象的复杂结构中进行选择,但是只有在foreach的帮助下,如何仅使用LINQ如何避免使用此foreach并解决我的问题?

I managed to make a selection from the complex structure of the object, but only with the help of foreach, how can I avoid this foreach and solve my problem, just using LINQ?

        var product = new List<ProductCrp>
        {
            new ProductCrp {
                Strucutre = new StructureItem() {
                    CheckList = new CheckList() {
                        Checks = new List<Check>
                        {
                            new Check { NumberAsInt = "149" },
                            new Check { NumberAsInt = "260" },
                            new Check { NumberAsInt = null }
                        }
                    }
                }
            },
            new ProductCrp {
                Strucutre = new StructureItem() {
                    CheckList = new CheckList() {
                        Checks = new List<Check>
                        {
                            new Check { NumberAsInt = "261" },
                            new Check { NumberAsInt = "150" },
                            new Check { NumberAsInt = "260" }
                        }
                    }
                }
            }
        };

        string[] numbers = { "149" };

LINQ:

        foreach (var item in product)
        {
            item.Strucutre.CheckList.Checks = item.Strucutre.CheckList.Checks.Where(w => numbers.Contains(w.NumberAsInt)).Select(w => w);
        }

推荐答案

我设法从对象的复杂结构中进行选择,但是只有在foreach的帮助下,如何仅使用LINQ就如何避免使用此foreach并解决我的问题?

I managed to make a selection from the complex structure of the object, but only with the help of foreach, how can I avoid this foreach and solve my problem, just using LINQ?

您不为此目的使用LINQ.您正在正确使用foreach.

You do not use LINQ for this purpose. You are using foreach correctly.

LINQ用于查询数据. foreach循环与反复产生副作用有关. foreach的主体正在变异对象的属性.这是 update ,而不是 query ,所以您做对了.为此使用LINQ是错误的.不要这样做.

LINQ is for querying data. A foreach loop is about producing a side effect repeatedly. The body of your foreach is mutating a property of an object; that's an update and not a query, so you are doing it right. Using LINQ for that is wrong; don't do it.

例如,使用ToList强制执行具有副作用的查询迭代的答案是极其糟糕的样式,并且导致代码效率低下,难以理解,难以执行维护并违背查询运算符的目的.永远不要滥用LINQ.我们在语言中内置了一个构造,该构造的意思是每个集合元素执行一次此操作",它称为foreach.使用它.

Answers that say to, for instance, use ToList to force iteration of a query with a side effect are extremely bad style and result in code which is inefficient, hard to understand, hard to maintain, and works against the purpose of the query operators. NEVER abuse LINQ like that. We have a construct built into the language that means "perform this operation once per collection element", and it is called foreach. Use it.

这篇关于LINQ C#复杂的嵌套结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆