0

I am coming from Perl doing first steps with C# and Linq. My question is if there is a way to put parts of a Linq statement in a variable like this (Code only for short illustration, not tested) to use it several times more easily and flexible than writing it new every time. Also one could use different Order-Statements (Select-Case, Array) for the same MQuery.

var orderstatement = "orderby m.Reihenfolge ascending, m.Datum descending, m.Titel ascending";

var MQuery = (from m in _context.Movie
               orderstatement
               where m.Sichtbar == true && m.Gesperrt == false
               select m;

Thanks for advising.

ikegami
  • 367,544
  • 15
  • 269
  • 518
Mirke
  • 1
  • 1
  • Yes-ish. You should learn about [Linq Method Syntax](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/query-syntax-and-method-syntax-in-linq#lambda-expressions). – gunr2171 Mar 31 '21 at 19:22
  • Does this answer your question? [Reuse of a LINQ query](https://stackoverflow.com/questions/34337294/reuse-of-a-linq-query) – gunr2171 Mar 31 '21 at 19:22
  • 1
    OrderBy yes, but better to post more details and samples. LINQ is complex thing from the first sign. – Svyatoslav Danyliv Mar 31 '21 at 19:55

1 Answers1

1

You can try something like this with extension methods. First, define the order by movies method

public static IQueryable<Movie> OrderMovies(this IQueryable<Movie> movies) {
         return movies.OrderBy(m => m.Reihenfolge).ThenByDescending(m => m.Datum).ThenBy(m => m.Title);
}

And then use it in the movies query

var movies = _context.Movies.Where(m => m.Sichtbar == true && m.Gesperrt == false).OrderMovies().Select(m => m)
Anton Kovachev
  • 322
  • 3
  • 6