将foreach和if转换为linq查询

本文关键字:linq 查询 转换 if foreach | 更新日期: 2023-09-27 18:08:43

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

我尝试将上面的foreach循环转换为linq查询,如下所示。

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

但是它给了我下面的错误@ l.Key

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

"

将foreach和if转换为linq查询

试试下面的代码。我认为这是正确的LINQ转换您的查询

 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;
        }
var schemaInfos = from db in SourceSchemaInfos
                  from table in db.SchemaInfos
                  from tableList in table.SchemaInfos
                  from selectedTable in SelectedTables
                  where tableList.Key == selectedTable.Key
                  select tableList.SchemaInfos;
foreach(var tableSchema in schemaInfos)
{
    tableSchema.IsSelected = true;
}