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)
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();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.