Linq代码不能正常工作
本文关键字:工作 常工作 代码 不能 Linq | 更新日期: 2023-09-27 18:13:54
我编写了以下代码,以便在网格视图中将复选框选中(true)的所有行的列值"lblJurisdiction"组合在一起
if (grdView.Rows.Count > 0)
{
foreach (GridViewRow row in grdView.Rows)
{
CheckBox chkbox = row.FindControl("chkbox") as CheckBox;
Label lblJurisdiction = row.FindControl("lblJurisdiction") as Label;
bool saveThis = chkbox.Checked;
if (saveThis == true)
{
List<String> Items = new List<String>();
Items.Add(lblJurisdiction.Text);
Items.Sort();
List<string> Unique = Items.Distinct().ToList();
string ReplacedJurisdiction = string.Join(",", Unique.ToArray());
hdnJurisdiction.Value = ReplacedJurisdiction;
}
}
}
例如,网格视图包含
- [true] [Alabama] [some value]
- [true] [Alaska] [some value]
- [false] [New York] [some value]
- [false] [California] [some value]
现在隐藏字段应该包含Alabama, Alaska它只合并了一个,即阿拉斯加…
你应该改变你的变量范围!您应该在foreach
循环外声明列表,并在完成计算后设置值。我还修改了你的代码,以匹配c#中常见的命名和编码约定。
if (grdView.Rows.Count > 0)
{
var states = new List<string>();
foreach (GridViewRow row in grdView.Rows)
{
var chkbox = row.FindControl("chkbox") as CheckBox;
if (chkbox.Checked)
{
var lblJurisdiction = row.FindControl("lblJurisdiction") as Label;
states.Add(lblJurisdiction.Text);
}
}
hdnJurisdiction.Value = string.Join(", ", states.Distinct().OrderBy(x => x));
}
您应该将字符串连接起来,现在您在隐藏字段
中覆盖它们if(hdnJurisdiction.Value.Length > 0 && ReplacedJurisdiction != "")
hdnJurisdiction.Value += ", ";
hdnJurisdiction.Value += ReplacedJurisdiction;
原始代码根本没有使用LINQ。选择所有选中行的标签的LINQ查询可以如下所示:
var labels= grdView.Rows.OfType<GridViewRow>()
.Where(row=>(row.FindControl("chkbox") as CheckBox)?.Checked)
.Select(row=>(row.FindControl("lblJurisdiction") as Label)?.Text)
.Distinct()
.OrderBy(x=>x);
或this,以查询形式:
var labels=(from row in grdView.Rows.OfType<GridViewRow>()
let chkbox = row.FindControl("chkbox") as CheckBox
let label=row.FindControl("lblJurisdiction") as Label
where chkbox.Checked
select label.Text)
.Distinct().OrderBy(x=>x);
一旦你有了所有的标签,你可以把它们连接起来:
var text=String.Join(labels);