Linq代码无法正常工作

时间:2016-10-19 06:34:38

标签: c# asp.net linq c#-4.0

我编写了以下代码,以便在网格视图中组合选中复选框(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] [阿拉巴马州] [有些价值]
  • [true] [阿拉斯加] [有些价值]
  • [false] [纽约] [有些价值]
  • [false] [加利福尼亚] [有些价值]

现在隐藏的区域应该包含阿拉巴马州阿拉巴马州 它只合并了一个,即阿拉斯加......

3 个答案:

答案 0 :(得分:3)

您应该更改变量范围!您应该在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));
}

答案 1 :(得分:1)

你应该连接字符串,现在你在隐藏字段中覆盖它们

if(hdnJurisdiction.Value.Length > 0 && ReplacedJurisdiction != "")
   hdnJurisdiction.Value += ", ";

hdnJurisdiction.Value += ReplacedJurisdiction;

答案 2 :(得分:0)

原始代码根本不使用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);

或者,以查询形式:

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);