[英]c# Linq String conversion
我想將一組 id 或 null 發送到此存儲庫中,並讓它返回完整列表或包含 id 的列表。
什么是最好的方法來做到這一點? UI 控件設置值類似於“1411,1413”,但是當沒有值時,我想返回所有數據。 就像我需要一個 或 之后包含
UI
if ($('#ddlGuidelines').val()) {
selectedGuidelineIds = $('#ddlGuidelines').val().toString();
}
$.ajax({
type: "POST",
url: '/Public/Reports/Handlers/Downloads.ashx',
data: { GuidelineIds": selectedGuidelineIds, "Action": "ByLinkTypes" },
中庭
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 很酷,因為它推遲執行,直到使用結果。 這意味着您可以有條件地將事物鏈接在一起,並且在需要之前不會執行實際查詢。
因此,回到您的原始代碼,您可以執行以下操作(假設過濾器類似於“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();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.