gpt4 book ai didi

c# - 如何比较 LINQ 中的多个复选框列表值,如 IN 子句 SQL

转载 作者:太空宇宙 更新时间:2023-11-03 12:27:16 26 4
gpt4 key购买 nike

在此代码中,“chklstDepartment”具有多个值,但正在显示,但仅为第一个选定项目绑定(bind)数据。如何为所有选定的复选框列表值绑定(bind)数据?

List<LessonLearnDetails> objLessonDetails = objLessonDashboard.getLessonLearntDetails();
var searchData = objLessonDetails
.Where(i => ddlAsset.SelectedValue == "0" ||
i._Asset.AssetID == ddlAsset.SelectedValue)
.Where(i => ddlAuditType.SelectedValue == "0" ||
i._Audit.AuditTypeID == ddlAuditType.SelectedValue)
.Where(i => chklstDepartment.SelectedValue == "0" ||
i._Department.DepartmentID == chklstDepartment.SelectedValue)
.Where(i => ddlStartYear.SelectedItem.Text == "--Select All--" ||
i._Year.StartYear == ddlStartYear.SelectedItem.Text)
.Where(i => ddlEndYear.SelectedItem.Text == "--Select All--" ||
i._Year.EndYear == ddlEndYear.SelectedItem.Text)
.Distinct()
.ToList();
BindGrid(searchData);

我还使用了一个函数来存储检查值,并使用 chklstDepartment.Contains() 传递了该值,但它返回 0。

for (int i = 0; i < chklstDepartment.Items.Count; i++)
{
if (chklstDepartment.Items[i].Selected)
{
chbstr += chklstDepartment.Items[i].Value + ",";
count++;
//if(count > 1)
}
var data = new string[] {chbstr};
}
chbstr = chbstr == string.Empty ? "0" : chbstr;
//chbstr = chklstDepartment.SelectedValue;
//chbstr = chbstr.Split(',').ToString();
return chbstr;

最佳答案

你不应该返回一个字符串,而是一个可枚举的字符串。您可以更改您的 where 语句。

类似于:

.Where(i => (chklstDepartment.SelectedValue == "0")
|| (chklstDepartment.Items.Cast<ListItem>()
.Where(item => item.Selected)
.Select(item => item.Value)
.Contains(i._Department.DepartmentID)))

如果 DepartmentID 是一个 int,你可以试试这个:

.Where(i => (chklstDepartment.SelectedValue == "0")
|| (chklstDepartment.Items.Cast<ListItem>()
.Where(item => item.Selected)
.Select(item => Convert.ToInt32(item.Value))
.Contains(i._Department.DepartmentID)))

您可以考虑缓存选择:

var selectedIds = chklstDepartment.Items.Cast<ListItem>()
.Where(item => item.Selected)
.Select(item => Convert.ToInt32(item.Value))
.ToArray(); // or ToList() or HashSet

.Where(i => (chklstDepartment.SelectedValue == "0")
|| (selectedIds.Contains(i._Department.DepartmentID)))

关于c# - 如何比较 LINQ 中的多个复选框列表值,如 IN 子句 SQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44263540/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com