【发布时间】:2021-10-06 13:27:36
【问题描述】:
我想使用这个字符串作为过滤器来删除 linq 查询中的一些 Id
public class ProductKitMakerDto
{
public int Id { get; set; }
public string TitleShort { get; set; }
public string Media { get; set; }
}
[HttpPost]
public ActionResult KitItemSelect(string culture)
{
string productMakerIds = "4174,2196,2201,2460,2508,2204";
//create a list
var productMakerList = new List<ProductKitMakerDto>();
foreach (int i in productMakerIds)
{
productMakerList.Add(new ProductKitMakerDto { Id = i });
}
var itemselects = (from p in _context.Products
where p.Matrix == 2400
select new ProductKitMakerDto()
{
Id = p.Id,
TitleShort = culture == "de" ? p.TitleShortDe :
culture == "fr" ? p.TitleShortFr :
p.TitleShortEn,
Media = "/img/" + p.Photo,
}).ToList();
//From this query I get 40 results.
//Then I want to remove the ones from the list:
//itemselects = itemselects.Where(i => !productMakerList.Any(pml =>pml.Id == i.Id));
//1st (above) I get an Error CS0266 asking for explicit cast. So aplly the modification
itemselects = (List<ProductKitMakerDto>)itemselects.Where(i => !productMakerList.Any(pml =>pml.Id == i.Id));
return Json(itemselects, JsonRequestBehavior.AllowGet);
}
我得到 500(内部服务器错误) - xhr.send( options.hasContent && options.data || null ); 我猜这个列表是空的。 任何想法?谢谢
【问题讨论】:
-
其中一个生产标记 id 是 4174 ??或 4
-
@behroozbc 4174!它们有一个逗号分隔符。
-
foreach (int i in productMakerIds)不起作用。您需要 Split 您的productMakerIds并将各个字符串解析为整数。 -
@Filburt:我试过 var productMakerList = ProductMakerIds.Split(',').Select(int.Parse).ToList();和 var productMakerList = ProductMakerIds.Split(',').ToList().Select(int.Parse).ToList();然后 itemselects = itemselects.Where(i => !productMakerList.Contains(i.Id));但我收到错误:在 System.Collections.Generic.List 中输入 System.Collections.Generic.IEnumerable
-
“要求显式转换”
Enumerable.Where不返回列表,因此将其转换为一个没有意义,而是在Where之后附加ToList。