Alter a view to show the first N results I created a view via the view user interface. From a custom module, I want alter the view for display the n firsts results depending of some user parameters. 

I don't find how I can do that with views alter hook functions. For example, via the pre execute view alter hook, I can get the query substructure. How can I configure this structure for not display all results by display only the first N  results? 

The "limit" value define the value in the current page with the current "level" of pager (10 results of the 27 results are displayed in pager 1, 10 results of the 27 results are displayed in pager 2 and 7 results of the 27 results are displayed in pager 3). The "limit" doesn't define the total number o, f the result query.



Thanks to Kevin answer, I tried this code. 

function mycustommodule_views_query_alter(ViewExecutable $view, \Drupal\views\Plugin\views\query\QueryPluginBase $query){

    if($views-&gt;id() == "mycustomview"){
        $view-&gt;query-&gt;setLimit(7);
        $view-&gt;query-&gt;setOffset(5);
        $view-&gt;save();

        // I try also ..
        // $query-&gt;setLimit(7);
        // $query-&gt;setOffset(5);
    }
}


My view in the view page doesn't change and displays 10 results (number total of nodes). How can I set Limit and/or Offset and 'save' the change from the hook view query alter? 

After Rémy's answer, I tried this code. 

function mymodule_views_query_alter(\Drupal\views\ViewExecutable $view, \Drupal\views\Plugin\views\query\QueryPluginBase $query){

    if($views-&gt;id() == "mycustomview"){
        $query-&gt;setLimit(3);
        ksm("Hey ! I pass here !"); // log function
    }
}


in drupal/modules/custom/mymodule/mymodule.module file

OR

in in drupal/modules/custom/mymodule/mymodule.views_execute.inc file

and I clear caches with "drush cr"

=> My view page display my log ("Hey ! I pass here !"), BUT, my view always display ALL result :/ Its crazy ! x)
You need to alter the pager, see ViewExecutable:initPager(), so right now only this code works (seems confusing ..):

function mycustommodule_views_query_alter(\Drupal\views\ViewExecutable $view, \Drupal\views\Plugin\views\query\QueryPluginBase $query){
    if($view-&gt;id() == 'mycustomview'){
        $view-&gt;setOffset(5);
        $view-&gt;getPager()-&gt;setItemsPerPage(7);
    }
}



  Is that code touched only the first time ? (After running drush cr)


If so - move the method in a file called mycustommodule.views_execution.inc. It won't work on every request inside mycustommodule.module file. see here!


  Also make sure Disable SQL rewriting is not set in the view used !


For more information see the issue I addressed regarding this on d.o.