0

I would like to send a group of id's or null into this repository and have it return the full list, or a list that contains the ids.

What would be the best way to do this? the UI control sets value would be something like "1411,1413" but when there is no value i want to return all the data. Its like I need an or after the Contains

UI if ($('#ddlGuidelines').val()) { selectedGuidelineIds = $('#ddlGuidelines').val().toString(); } $.ajax({ type: "POST", url: '/Public/Reports/Handlers/Downloads.ashx', data: { GuidelineIds": selectedGuidelineIds, "Action": "ByLinkTypes" }, 

middle Teir

 public Nullable<int> Id{ get; set; } public Model.FilterOptions GetOptionsByIds(List<int?> Ids) { using (var db = new DLEntities()) { var list = (from pg in db.list where Ids.Contains(pg.Id) 
7
  • 1
    The problem is in the generation of the original list, How are you generating the string IDs? That should be where the list of int IDs is created. Commented Jan 6, 2020 at 20:12
  • Basic design question - why are you filtering a column of integers (which may be null) by a single (presumably delimter-separated) string? You will need validation What if the string passed in is "1,2, 3, GooblyGook123 "? Take a look at your design, and this may solve itself. Commented Jan 6, 2020 at 20:12
  • the original list is a drop down control where the user can select one or many items in the list Commented Jan 6, 2020 at 20:14
  • Can you show the code where you capture the input from the dropdown control. That's where you need to generate the list. Commented Jan 6, 2020 at 20:17
  • @PeterSmith the UI will send "1411,1413" to the middle teir but what do i do when I want the full list? The list will have a count of 0 Commented Jan 6, 2020 at 20:33

1 Answer 1

1

LINQ is cool because it defers execution until the result is used. That means you can conditionally chain things together, and the actual query will not be executed until needed.

So, going back to your original code, you can do something like this (assuming the filter is something like "1,2,3"):

public Model.FilterOptions GetOptionsById(string filter) { using (var db = new DLEntities()) { var list = db.Select(item => item); // Just get the entire list by default // If the filter is provided if (! string.IsNullOrWhitespace(filter)) { // If you cannot insure that your filter is valid... // SomeValidationMethod(); // Split the filter string into a list of strings, // and then parse each of those strings into an int, // returning the whole thing in an anonymous IEnumerable<int> var intFilter = filter.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries) .Select(int.Parse); // Finally, filter the list by those integers list = list.Where(item => intFilter.Contains(item.Id)); } // Calling ToList() will finally actually execute the query, // either with or without the filter return list.ToList(); } 
Sign up to request clarification or add additional context in comments.

Comments