LINQ C# complex nesting structure

前端 未结 2 476
旧时难觅i
旧时难觅i 2021-01-14 18:10

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

相关标签:
2条回答
  • 2021-01-14 18:36

    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());
    
    0 讨论(0)
  • 2021-01-14 18:51

    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.

    0 讨论(0)
自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题