0

I am trying to write a LINQ statement that will pull all the items from a table where the column Type matches what the user selects in a dropdown menu but if no matches are found then it returns ALL the items from the table regardless of the Type. I have gotten it to return all the items that match the user’s selection but I cannot figure out what code needs to be added so that if no matches are found it defaults to pulling all the items in the table.

Current Code:

(from i in db.ItemTypeTranslations
    join st in db.SectionTranslations
    on i.ItemType.SectionID equals st.SectionID
    where i.CultureID == 1 && i.ItemType.SectionID == SelectedSection
    select new
    {
       st.SectionID,
       st.Title,
       i.ItemTypeName
    }).ToList();

3 Answers3

1

How about

where i.CultureID == 1 && (i.ItemType.SectionID == SelectedSection || String.IsNullOrEmpty(SelectedSection))

I am assuming that SelectedSection is a string. If not, the principle will be the same: Where (SectionID == SelectedSection OR SelectedSection == some-default-value)

Edit: I just re-read your question, and realized that I'm answering the wrong question.

Alan Gilbert
  • 365
  • 2
  • 9
1

You can use the ? operator to turn your where clause into a conditional and have your current select as the successful branch and the select that returns everything as the unsuccessful branch.

Similar question asked on MSDN

Maggy May
  • 233
  • 1
  • 7
1

Thanks Maggy May. That helped me a lot I ended up with this code that looks to be working:

(from i in db.ItemTypeTranslations
                                          join st in db.SectionTranslations
                                          on i.ItemType.SectionID equals st.SectionID
                                          where (SelectedSection == 0 ? true : i.ItemType.SectionID == SelectedSection) && i.CultureID == 1
                                          select new
                                          {
                                              i.ItemTypeID,
                                              st.Title,
                                              i.ItemTypeName
                                          }).ToList();
  • The orginal code I posted here was not working but with a slight tweek it is working now. I updated the code block with the confirmed working code. –  May 01 '13 at 00:55