Tibomso
Tibomso

Reputation: 373

LINQ C# complex nesting structure

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);
        }

Upvotes: 4

Views: 1725

Answers (2)

Eric Lippert
Eric Lippert

Reputation: 660024

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?

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

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.

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.

Upvotes: 19

Ayaz
Ayaz

Reputation: 2121

Are you looking for something like this?

product.ForEach(item => item.Strucutre.CheckList.Checks = item.Strucutre.CheckList.Checks.Where(w => numbers.Contains(w.NumberAsInt)).Select(w => w).ToList());

Upvotes: 0

Related Questions