Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. LINQ
  4. How can I make one query out of many others

How can I make one query out of many others

Scheduled Pinned Locked Moved LINQ
questiondatabasehelptutorial
12 Posts 3 Posters 32 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • U Offline
    U Offline
    User 11883281
    wrote on last edited by
    #1

    I've this code: (it's much longer...)

    if (selection == "bild" )
    {
    erg = from item in _db.object_1
    where item.article_number != null
    && item.bild == null
    && item.brand.StartsWith(marke)
    && ( item.o_path.StartsWith(pathwerkzeug) || item.o_path.StartsWith(pathgarten))
    select item.article_number;
    }
    else if (selection == "machine_group")
    {
    erg = from item in _db.object_1
    where item.article_number != null
    && item.machine_group == null
    && item.brand.StartsWith(marke)
    && (item.o_path.StartsWith(pathwerkzeug) || item.o_path.StartsWith(pathgarten))
    select item.article_number;
    }

    How can I shorten it? Can I get a Variable for for example "item.bild"? Its always the same... if the selection is "bild" I will ask if "item.bild" is null; if the selection is "machine_group" I will ask if "item.machine_group" is null Can you help me?

    Richard DeemingR 1 Reply Last reply
    0
    • U User 11883281

      I've this code: (it's much longer...)

      if (selection == "bild" )
      {
      erg = from item in _db.object_1
      where item.article_number != null
      && item.bild == null
      && item.brand.StartsWith(marke)
      && ( item.o_path.StartsWith(pathwerkzeug) || item.o_path.StartsWith(pathgarten))
      select item.article_number;
      }
      else if (selection == "machine_group")
      {
      erg = from item in _db.object_1
      where item.article_number != null
      && item.machine_group == null
      && item.brand.StartsWith(marke)
      && (item.o_path.StartsWith(pathwerkzeug) || item.o_path.StartsWith(pathgarten))
      select item.article_number;
      }

      How can I shorten it? Can I get a Variable for for example "item.bild"? Its always the same... if the selection is "bild" I will ask if "item.bild" is null; if the selection is "machine_group" I will ask if "item.machine_group" is null Can you help me?

      Richard DeemingR Offline
      Richard DeemingR Offline
      Richard Deeming
      wrote on last edited by
      #2

      You can extract the common part of the query, and apply the additional filters to that common part:

      var query = from item in _db.object_1
      where item.article_number != null
      && item.brand.StartsWith(marke)
      && (item.o_path.StartsWith(pathwerkzeug) || item.o_path.StartsWith(pathgarten));

      if (selection == "bild" || selection == "Alle")
      {
      erg = from item in query
      where item.bild == null
      select item.article_number;
      }
      else if (selection == "machine_group") // || selection == "Alle")
      {
      erg = from item in query
      where item.machine_group == null
      select item.article_number;
      }

      NB: There's no point having selection == "Alle" in your else if test. If selection == "Alle", your code will execute the if branch, and ignore the else if branch. If you've got a lot of branches, you should probably look at using a switch block:

      var query = from item in _db.object_1
      where item.article_number != null
      && item.brand.StartsWith(marke)
      && (item.o_path.StartsWith(pathwerkzeug) || item.o_path.StartsWith(pathgarten));

      switch (selection)
      {
      case "bild":
      case "Alle":
      {
      erg = from item in query
      where item.bild == null
      select item.article_number;
      break;
      }
      case "machine_group":
      {
      erg = from item in query
      where item.machine_group == null
      select item.article_number;
      break;
      }
      }


      "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

      "These people looked deep within my soul and assigned me a number based on the order in which I joined" - Homer

      U 1 Reply Last reply
      0
      • Richard DeemingR Richard Deeming

        You can extract the common part of the query, and apply the additional filters to that common part:

        var query = from item in _db.object_1
        where item.article_number != null
        && item.brand.StartsWith(marke)
        && (item.o_path.StartsWith(pathwerkzeug) || item.o_path.StartsWith(pathgarten));

        if (selection == "bild" || selection == "Alle")
        {
        erg = from item in query
        where item.bild == null
        select item.article_number;
        }
        else if (selection == "machine_group") // || selection == "Alle")
        {
        erg = from item in query
        where item.machine_group == null
        select item.article_number;
        }

        NB: There's no point having selection == "Alle" in your else if test. If selection == "Alle", your code will execute the if branch, and ignore the else if branch. If you've got a lot of branches, you should probably look at using a switch block:

        var query = from item in _db.object_1
        where item.article_number != null
        && item.brand.StartsWith(marke)
        && (item.o_path.StartsWith(pathwerkzeug) || item.o_path.StartsWith(pathgarten));

        switch (selection)
        {
        case "bild":
        case "Alle":
        {
        erg = from item in query
        where item.bild == null
        select item.article_number;
        break;
        }
        case "machine_group":
        {
        erg = from item in query
        where item.machine_group == null
        select item.article_number;
        break;
        }
        }


        "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

        U Offline
        U Offline
        User 11883281
        wrote on last edited by
        #3

        I know.. the "else if" have to be an "if" please ignor it Thank you thats much shorter... but maybe its going shorter?

        P Richard DeemingR 2 Replies Last reply
        0
        • U User 11883281

          I know.. the "else if" have to be an "if" please ignor it Thank you thats much shorter... but maybe its going shorter?

          P Offline
          P Offline
          Pete OHanlon
          wrote on last edited by
          #4

          Why not use the Dynamic LINQ Library to do this? Here's some useful info: ScottGu[^].

          U 1 Reply Last reply
          0
          • P Pete OHanlon

            Why not use the Dynamic LINQ Library to do this? Here's some useful info: ScottGu[^].

            U Offline
            U Offline
            User 11883281
            wrote on last edited by
            #5

            Thank you, but I do not have experience in dynamic Linq, and i don't have time to study it now, isn't there any other way?

            P 1 Reply Last reply
            0
            • U User 11883281

              Thank you, but I do not have experience in dynamic Linq, and i don't have time to study it now, isn't there any other way?

              P Offline
              P Offline
              Pete OHanlon
              wrote on last edited by
              #6

              No, there isn't and Dynamic LINQ isn't hard - you could have learned it in the time you waited for my reply. Honestly, it looks like you didn't even read the link I put in the previous post - if you had, you'd have seen that you can mix and match your standard "from x in ...." syntax with Dynamic LINQ, so you only need to touch the one place.

              1 Reply Last reply
              0
              • U User 11883281

                I know.. the "else if" have to be an "if" please ignor it Thank you thats much shorter... but maybe its going shorter?

                Richard DeemingR Offline
                Richard DeemingR Offline
                Richard Deeming
                wrote on last edited by
                #7

                Not sure it's technically shorter, but you could build a dictionary to map your selection variable to a filter, and store that map as a private field in your class:

                private static readonly Dictionary<string, Expression<Func<object_1, bool>>> Filters = new Dictionary<string, Expression<Func<object_1, bool>>>
                {
                { "bild", item => item.bild == null },
                { "machine_group", item => item.machine_group == null },
                };

                You would then use that dictionary to look up the filter:

                var query = from item in _db.object_1
                where item.article_number != null
                && item.brand.StartsWith(marke)
                && (item.o_path.StartsWith(pathwerkzeug) || item.o_path.StartsWith(pathgarten));

                Expression<Func<object_1, bool>> filter;
                if (Filters.TryGetValue(selection, out filter))
                {
                query = query.Where(filter);
                }

                erg = query.Select(item => item.article_number);


                "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

                "These people looked deep within my soul and assigned me a number based on the order in which I joined" - Homer

                U 2 Replies Last reply
                0
                • Richard DeemingR Richard Deeming

                  Not sure it's technically shorter, but you could build a dictionary to map your selection variable to a filter, and store that map as a private field in your class:

                  private static readonly Dictionary<string, Expression<Func<object_1, bool>>> Filters = new Dictionary<string, Expression<Func<object_1, bool>>>
                  {
                  { "bild", item => item.bild == null },
                  { "machine_group", item => item.machine_group == null },
                  };

                  You would then use that dictionary to look up the filter:

                  var query = from item in _db.object_1
                  where item.article_number != null
                  && item.brand.StartsWith(marke)
                  && (item.o_path.StartsWith(pathwerkzeug) || item.o_path.StartsWith(pathgarten));

                  Expression<Func<object_1, bool>> filter;
                  if (Filters.TryGetValue(selection, out filter))
                  {
                  query = query.Where(filter);
                  }

                  erg = query.Select(item => item.article_number);


                  "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

                  U Offline
                  U Offline
                  User 11883281
                  wrote on last edited by
                  #8

                  Thank you that looks good, i will try it.

                  1 Reply Last reply
                  0
                  • Richard DeemingR Richard Deeming

                    Not sure it's technically shorter, but you could build a dictionary to map your selection variable to a filter, and store that map as a private field in your class:

                    private static readonly Dictionary<string, Expression<Func<object_1, bool>>> Filters = new Dictionary<string, Expression<Func<object_1, bool>>>
                    {
                    { "bild", item => item.bild == null },
                    { "machine_group", item => item.machine_group == null },
                    };

                    You would then use that dictionary to look up the filter:

                    var query = from item in _db.object_1
                    where item.article_number != null
                    && item.brand.StartsWith(marke)
                    && (item.o_path.StartsWith(pathwerkzeug) || item.o_path.StartsWith(pathgarten));

                    Expression<Func<object_1, bool>> filter;
                    if (Filters.TryGetValue(selection, out filter))
                    {
                    query = query.Where(filter);
                    }

                    erg = query.Select(item => item.article_number);


                    "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

                    U Offline
                    U Offline
                    User 11883281
                    wrote on last edited by
                    #9

                    Okay now I get a few errors... 1.:

                    A query body must end with a select clause or a group clause

                    2.:

                    'System.Collections.Generic.IEnumerable' does not contain a definition for 'Where' and the best extension method overload 'System.Linq.Queryable.Where(System.Linq.IQueryable, System.Linq.Expressions.Expression>)' has some invalid arguments

                    3.:

                    The type of the expression in the select clause is incorrect. Type inference failed in the call to 'Select'.

                    4.:

                    The type arguments for method 'System.Linq.Enumerable.Select(System.Collections.Generic.IEnumerable, System.Func)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

                    5.:

                    Instance argument: cannot convert from 'System.Collections.Generic.IEnumerable' to 'System.Linq.IQueryable'

                    Richard DeemingR 1 Reply Last reply
                    0
                    • U User 11883281

                      Okay now I get a few errors... 1.:

                      A query body must end with a select clause or a group clause

                      2.:

                      'System.Collections.Generic.IEnumerable' does not contain a definition for 'Where' and the best extension method overload 'System.Linq.Queryable.Where(System.Linq.IQueryable, System.Linq.Expressions.Expression>)' has some invalid arguments

                      3.:

                      The type of the expression in the select clause is incorrect. Type inference failed in the call to 'Select'.

                      4.:

                      The type arguments for method 'System.Linq.Enumerable.Select(System.Collections.Generic.IEnumerable, System.Func)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

                      5.:

                      Instance argument: cannot convert from 'System.Collections.Generic.IEnumerable' to 'System.Linq.IQueryable'

                      Richard DeemingR Offline
                      Richard DeemingR Offline
                      Richard Deeming
                      wrote on last edited by
                      #10

                      I suspect they're all related. Try adding a select clause to the end of the first query:

                      var query = from item in _db.object_1
                      where item.article_number != null
                      && item.brand.StartsWith(marke)
                      && (item.o_path.StartsWith(pathwerkzeug) || item.o_path.StartsWith(pathgarten))
                      select item;


                      "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

                      "These people looked deep within my soul and assigned me a number based on the order in which I joined" - Homer

                      U 1 Reply Last reply
                      0
                      • Richard DeemingR Richard Deeming

                        I suspect they're all related. Try adding a select clause to the end of the first query:

                        var query = from item in _db.object_1
                        where item.article_number != null
                        && item.brand.StartsWith(marke)
                        && (item.o_path.StartsWith(pathwerkzeug) || item.o_path.StartsWith(pathgarten))
                        select item;


                        "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

                        U Offline
                        U Offline
                        User 11883281
                        wrote on last edited by
                        #11

                        Thanks ;) it WAS working ... and then I changed it for all and now theres this errro:

                        System.TypeInitializationException: Der Typeninitialisierer für "Quälix.AbfrageIsNull" hat eine Ausnahme verursacht. ---> System.ArgumentException: Ein Element mit dem gleichen Schlüssel wurde bereits hinzugefügt.
                        bei System.ThrowHelper.ThrowArgumentException(ExceptionResource resource)
                        bei System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)
                        bei System.Collections.Generic.Dictionary`2.Add(TKey key, TValue value)
                        bei Quälix.AbfrageIsNull..cctor() in q:\PIM_PolicingTool\Quälix\Quälix\AbfrageIsNull.cs:Zeile 12.
                        --- Ende der internen Ausnahmestapelüberwachung ---
                        bei Quälix.AbfrageIsNull.ArtikelAufNullPruefen(String selection, List`1 marken)
                        bei Quälix.Form1.btAbfragIsNullSuche_Click(Object sender, EventArgs e) in q:\PIM_PolicingTool\Quälix\Quälix\Form1.cs:Zeile 56.

                        this is my code:

                        if (chbAbfrageArtikel.Checked == true)
                        {
                        endErgebnis += "ARTIKEL:";
                        endErgebnis += Environment.NewLine;
                        string zwischenErg = AbfrageIsNull.ArtikelAufNullPruefen(selection, marken);

                                        if (zwischenErg == "") { endErgebnis += "Alles zugeordnet"; }
                                        else { endErgebnis += zwischenErg; }
                        
                                        endErgebnis += Environment.NewLine;
                                        endErgebnis += Environment.NewLine;
                                    }
                                    if (chbAbfrageZubehoer.Checked == true)
                                    {
                                        endErgebnis += "ZUBEHÖR:";
                                        endErgebnis += Environment.NewLine;
                                        string zwischenErg =  "";// AbfrageIsNull.ZubehoerAufNullPruefen(selection, marken);
                        
                                        if (zwischenErg == "") { endErgebnis += "Alles zugeordnet"; }
                                        else { endErgebnis += zwischenErg; }
                        
                                        endErgebnis += Environment.NewLine;
                                        endErgebnis += Environment.NewLine;
                                    }
                                    if (chbAbfrageErsatzteil.Checked == true)
                                    {
                                        endErgebnis += "ERSATZTEILE:";
                                        endErgebnis += Environment.NewLine;
                                        string zwischenErg = "";// AbfrageIsNull.ErsatzteilAufNullPruefen(selection, marken);                    
                                        if (zwischenErg == "") { endErgebnis += "Alles zugeordnet"; }
                                        else { endErgebnis += zwischenErg; }
                        
                        Richard DeemingR 1 Reply Last reply
                        0
                        • U User 11883281

                          Thanks ;) it WAS working ... and then I changed it for all and now theres this errro:

                          System.TypeInitializationException: Der Typeninitialisierer für "Quälix.AbfrageIsNull" hat eine Ausnahme verursacht. ---> System.ArgumentException: Ein Element mit dem gleichen Schlüssel wurde bereits hinzugefügt.
                          bei System.ThrowHelper.ThrowArgumentException(ExceptionResource resource)
                          bei System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)
                          bei System.Collections.Generic.Dictionary`2.Add(TKey key, TValue value)
                          bei Quälix.AbfrageIsNull..cctor() in q:\PIM_PolicingTool\Quälix\Quälix\AbfrageIsNull.cs:Zeile 12.
                          --- Ende der internen Ausnahmestapelüberwachung ---
                          bei Quälix.AbfrageIsNull.ArtikelAufNullPruefen(String selection, List`1 marken)
                          bei Quälix.Form1.btAbfragIsNullSuche_Click(Object sender, EventArgs e) in q:\PIM_PolicingTool\Quälix\Quälix\Form1.cs:Zeile 56.

                          this is my code:

                          if (chbAbfrageArtikel.Checked == true)
                          {
                          endErgebnis += "ARTIKEL:";
                          endErgebnis += Environment.NewLine;
                          string zwischenErg = AbfrageIsNull.ArtikelAufNullPruefen(selection, marken);

                                          if (zwischenErg == "") { endErgebnis += "Alles zugeordnet"; }
                                          else { endErgebnis += zwischenErg; }
                          
                                          endErgebnis += Environment.NewLine;
                                          endErgebnis += Environment.NewLine;
                                      }
                                      if (chbAbfrageZubehoer.Checked == true)
                                      {
                                          endErgebnis += "ZUBEHÖR:";
                                          endErgebnis += Environment.NewLine;
                                          string zwischenErg =  "";// AbfrageIsNull.ZubehoerAufNullPruefen(selection, marken);
                          
                                          if (zwischenErg == "") { endErgebnis += "Alles zugeordnet"; }
                                          else { endErgebnis += zwischenErg; }
                          
                                          endErgebnis += Environment.NewLine;
                                          endErgebnis += Environment.NewLine;
                                      }
                                      if (chbAbfrageErsatzteil.Checked == true)
                                      {
                                          endErgebnis += "ERSATZTEILE:";
                                          endErgebnis += Environment.NewLine;
                                          string zwischenErg = "";// AbfrageIsNull.ErsatzteilAufNullPruefen(selection, marken);                    
                                          if (zwischenErg == "") { endErgebnis += "Alles zugeordnet"; }
                                          else { endErgebnis += zwischenErg; }
                          
                          Richard DeemingR Offline
                          Richard DeemingR Offline
                          Richard Deeming
                          wrote on last edited by
                          #12

                          The error message is quite clear - "An item with the same key has already been added". In your dictionary initializer, you have added the key "Inventurart" twice - the 6th and 29th items. Remove one of those items.


                          "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

                          "These people looked deep within my soul and assigned me a number based on the order in which I joined" - Homer

                          1 Reply Last reply
                          0
                          Reply
                          • Reply as topic
                          Log in to reply
                          • Oldest to Newest
                          • Newest to Oldest
                          • Most Votes


                          • Login

                          • Don't have an account? Register

                          • Login or register to search.
                          • First post
                            Last post
                          0
                          • Categories
                          • Recent
                          • Tags
                          • Popular
                          • World
                          • Users
                          • Groups