Search code examples
c#linqlinq-query-syntax

convert foreach and if to linq queries


  foreach (SchemaInfo db in SourceSchemaInfos)
            {
                foreach (SchemaInfo table in db.SchemaInfos)
                {
                    foreach (SchemaInfo tablelist in table.SchemaInfos)
                    {
                        for (int i = 0; i < SelectedTables.Count; i++)
                        {
                            if (tablelist.Key == SelectedTables[i].Key)
                            {
                                foreach (SchemaInfo _tableschema in tablelist.SchemaInfos)
                                {
                                    _tableschema.IsSelected = true;
                                }
                            }
                        }
                    }
                }
            }

i tried to convert the above foreach loop into linq queries as below..

  SourceSchemaInfos.ForEach(Database =>Database.SchemaInfos.ForEach(items => items.SchemaInfos.ForEach(tables => tables.SchemaInfos.Where(tables.Key == SelectedTables.ForEach(l => l.Key)).ForEach(m => m.IsSelected = true))));

but it thorws me the below error @ l.Key

CS0201  Only assignment, call, increment, decrement, and new object expressions can be used as a statement

`


Solution

  • Try the following code. I think this is correct LINQ conversion of your query

     foreach (var _tableschema in 
                (from db in SourceSchemaInfos from table in db.SchemaInfos from tablelist in table.SchemaInfos 
                 select tablelist)
                .SelectMany(tablelist => SelectedTables.Where(t => tablelist.Key == t.Key)
                    .SelectMany(t => tablelist.SchemaInfos)
                    ))
            {
                _tableschema.IsSelected = true;
            }