DataTable过滤处理

构建一个datatable:

 DataTable dt = new DataTable();
            dt.Columns.Add("customid");
            for (int i = 0; i < 10; i++)
            {
                DataRow dr = dt.NewRow();
                dr["customid"] = i.ToString();
                dt.Rows.Add(dr);
            }
添加新列Add方法就可以了,假如要插到某一列后面呢,可以用SetOrdinal(int ordinal)方法:

/// 
        /// 从目标字符串中查找
        /// 
        /// 要查找的字符串
        /// 
        private List GetObjItemsFromList(string findstr)
        {
            string[] arry = { "01 张三 男", "02 李四 男", "03 王五 女" };
            return arry.ToList().FindAll(delegate(string str) { return str.Contains(findstr); });
        }

DataTable dt_excel = ds.Tables[0];
                dt_excel.Columns.Add("new_sex").SetOrdinal(3);//添加新列new_sex并插入到第四列(序号)的位置
                for (int i = 0; i < dt_excel.Rows.Count; i++)
                    dt_excel.Rows[i]["new_sex"] = dt_excel.Rows[i]["e_sex"].ToString() == "0" ? "男" : "女";

                dt_excel.Columns.Remove("e_sex");//移除掉


方法一:

        using (ds = ....)
        {
            if (ds != null && ds.Tables[0].Rows.Count > 0)
            {
                System.Text.StringBuilder temp_dept_id = new System.Text.StringBuilder();
                ds.Tables[0].DefaultView.ToTable(true, "HR_DEPT_ID").AsEnumerable().ToList().ForEach(x => { temp_dept_id.Append(FormateAddString(x["HR_DEPT_ID"].ToString())); });
                if (string.IsNullOrEmpty(temp_dept_id.ToString())) return;
                strWhere += " AND HR_DEPT_ID in(" + temp_dept_id.ToString().TrimEnd(',') + ")";
            }
        }

/// 
    /// 格式化字符串
    /// 
    private string FormateAddString(string paramstr)
    {
        return !string.IsNullOrEmpty(paramstr) ? (paramstr + ",") : "";
    }

方法二:

通过实现IEqualityComparer接口成员方法

/// 
    /// 去掉DataTable重复项
    /// 
    /// 实现IEqualityComparer接口成员方法
    public class DataTableRowCompare : IEqualityComparer
    {
        public DataTableRowCompare()
        {
        }
        public DataTableRowCompare(string filedname)
        {
            _fieldname = filedname;
        }
        private string _fieldname = "id";
        public string fieldName
        {
            get { return _fieldname; }
            set { _fieldname = value; }
        }
        public bool Equals(DataRow x, DataRow y)
        {
            return (x.Field(fieldName) == y.Field(fieldName));
        }
        public int GetHashCode(DataRow obj)
        {
            return obj.ToString().GetHashCode();
        }
    }
using (DataSet postDS = .....)
        {
            DataTable _resultDt = postDS.Tables[0].AsEnumerable().Distinct(new DataTableRowCompare("POST_NAME")).CopyToDataTable();
            CCBindDropDownList(this.ddlPostionName, _resultDt, "POST_NAME", "HR_DEPT_PATH", new ListItem());
        }



你可能感兴趣的:(ASP.NET,C#)