复选框列出了linq的状态
本文关键字:状态 linq 复选框 | 更新日期: 2023-09-27 18:13:16
考虑这个场景,您希望检索checkboxlist中所有未选中复选框的值的List或IEnumerable。这段代码给出了所有选中的值(现在)或(以前)。如何使用linq获取未检查(现在)和(以前)的值?谢谢你
private IEnumerable <string > selectedValues
{
get
{
if (ViewState ["selectedValues"] == null && chapp . SelectedIndex >=-1 )
{
ViewState ["selectedValues"]= chapp .Items.Cast <ListItem >()
.Where (li=>li.Selected )
.Select (li=>li.Value )
.ToList ();
}else
ViewState ["selectedValues"]= Enumerable .Empty <string >();
return (IEnumerable <string >)ViewState ["selectedValues"];
}
set {ViewState ["selectedValues"] = value ;}
}
protected void chapp_SelectedIndexChanged(Object sender, EventArgs e)
{
CheckBoxList c = (CheckBoxList)sender;
var oldselection = this.selectedValues;
var newSelection = c.Items.Cast<ListItem>()
.Where(li => li.Selected )
.Select(li => li.Value);
var unchangedItems = newSelection.Except(oldselection );
}
根据你的评论:让我们说,你有aspx页面加载所有的应用程序,你有(从活动目录,数据库或其他),之后分配所有的应用程序,当前用户有(也从任何获得这些应用程序)…所以在你的Page_Load中你会有如下内容:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//Load all applications
var apps = loadAllApplications();
//Load user applications
var myApps = loadUserApplications();
//Bind to checkboxlist, assuming my checkboxlist ID "chksApps"
chksApps.DataSource = apps.Select(x => new ListItem
{
Value = x.Id.ToString(),
Text = x.Name,
Selected = myApps.Any(a => x.Id == a)
});
chksApps.DataBind();
}
}
//lets say I have a Application class like that
public class Application
{
public int Id { get; set; }
public string Name { get; set; }
}
private List<int> loadUserApplications()
{
// if user already have "Paint", "Chrome" assigned
var myApps = new List<int>() { 2, 4 };
return myApps;
}
private List<Application> loadAllApplications()
{
//for testing I will create a dummy list of applications
var applications = new List<Application>() {
new Application { Id = 1, Name = "Visual Studio" },
new Application { Id = 2, Name = "Paint" },
new Application { Id = 3, Name = "Notepad" },
new Application { Id = 4, Name = "Chrome" }
};
return applications;
}
所以到目前为止,用户可以勾选或取消勾选任何他想要的。所以你的复选框AutoPostBack = False
所以当他完成编辑后,假设他将提交给服务器那么他将有一个提交按钮(假设它的ID是"btnSave"
) protected void btnSave_Click(object sender, EventArgs e)
{
//Load user applications
var myApps = loadUserApplications();
//get selected Application
var selectedApps = chksApps.Items.Cast<ListItem>()
.Where(x => x.Selected)
.Select(x => int.Parse(x.Value)).ToList();
// send request to owner to add those below apps for user "newSelectedApps"
var newSelectedApps = selectedApps.Except(myApps).ToList();
// send request to owner to remove those below apps "newUnSelectedApps"
var newUnSelectedApps = myApps.Except(selectedApps).ToList();
// those below are the unchanged apps "unChangedApps"
var unChangedApps = myApps.Intersect(selectedApps).ToList();
}
这比使用ViewState
更好