一些感觉常用的扩展方法. ..

在平时的写代码过程中,突发随想而编写、收集到的一些扩展方法,呵呵既然C#提供这么好的语言特性,有些地方真的有利于我们程序员偷懒了 ..呼呼~~~~回应 熊哥 的提议 就分享出来了 ..也希望各位看官能提出里面的不足. ..:

一、对 System.String 的扩展:

 

For System.String
1 /// <summary>
2 /// 指定格式化字符串序列格式化当前字符串实例。
3 /// </summary>
4 /// <param name="source">当前字符串实例</param>
5 /// <param name="args">格式化字符串序列</param>
6 /// <exception cref="System.ArgumentNullException">空参数引用</exception>
7 /// <exception cref="System.FormatException">格式化错误</exception>
8 /// <returns></returns>
9   public static string FormatWith(this string source, params string[] args)
10 {
11 return string.Format(source, args);
12 }
// 调用方式: "如果是{0},请选择{1};否则请选择{3}".FormatWith("","","");//参数可以来自其他变量的值..就是
//原先 string.Format 的进一步修饰 ..o(∩_∩)o
13
14 /// <summary>
15 /// 使用指定的格式化方式修饰当前 <see cref="System.String"/> 实例。
16 /// </summary>
17 /// <param name="source">The source.</param>
18 /// <param name="formatter">格式化器,包含有且仅有一个{0}字符位置。</param>
19 /// <returns></returns>
20   public static string SurroundWith(this string source, string formatter)
21 {
22 if (String.IsNullOrEmpty(source))
23 return string.Empty;
24 return string.Format(formatter, source);
25 }
// 调用方式: "党中央学习关于.net4(C#4.0)的一些建议~~".SurroundWith("<p>{0}</p>");
      //=> 输出: <p>...</p>

 

 

 

 二、对 Sytem.Data.DataTable 的扩展;

  平时会写很多和数据库打交道的程序,DataTable应该是很经常用到的 ..

 

For System.Data.DataTable
#region --- For System.Data.DataTable ---

#region --- 求值 ---

/// <summary>
/// 判断当前 <see cref="System.Data.DataTable"/> 是否是 Null 或者包含空行。
/// </summary>
/// <param name="table">当前 <see cref="System.Data.DataTable"/> </param>
/// <returns></returns>
public static bool IsNullOrEmpty(this DataTable table)
{
return table == null || table.Rows.Count == 0;
}

/// <summary>
/// 获取指定行列的强类型的值。当指定的单元为Null 时,返回指定列字段 <typeparamref name="T"/>类型默认值。
/// </summary>
/// <typeparam name="T">字段的类型</typeparam>
/// <param name="table"></param>
/// <param name="rowIndex">行索引</param>
/// <param name="colIndex">列索引</param>
public static T FieldAt<T>(this DataTable table, int rowIndex, int colIndex)
{
if (table.IsNullOrEmpty())
return default(T);
if (table.Rows.Count < rowIndex || (table.Columns.Count < colIndex))
return default(T); ;
return table.Rows[rowIndex].Field<T>(colIndex);
}

/// <summary>
/// 获取指定行、列的强类型的值。遇到空值时,返回指定的默认值。
/// </summary>
/// <typeparam name="T">字段的类型</typeparam>
/// <param name="table"></param>
/// <param name="rowIndex">行索引</param>
/// <param name="colIndex">列索引</param>
/// <param name="defaultValue">当指定的单元为Null 时,返回这个值。</param>
/// <returns></returns>
public static T FieldAt<T>(this DataTable table, int rowIndex, int colIndex, T defaultValue)
{
if (table.IsNullOrEmpty())
return defaultValue;
if (table.Rows.Count < rowIndex || (table.Columns.Count < colIndex))
return defaultValue;
return table.Rows[rowIndex].Field<T>(colIndex);
}


/// <summary>
/// 获取指定行列的 <see cref="System.String"/> 值。
/// </summary>
/// <param name="table"></param>
/// <param name="rowIndex">行所引</param>
/// <param name="colIndex">列所引</param>
/// <returns></returns>
public static string FieldAt(this DataTable table, int rowIndex, int colIndex)
{
if (table.IsNullOrEmpty())
return string.Empty;

if (table.Rows.Count < rowIndex || (table.Columns.Count < colIndex))
return string.Empty;
object o = null;

o
= table.Rows[rowIndex][colIndex];

return o == null ? string.Empty : o.ToString();
}

/// <summary>
/// 获取指定行列的 <see cref="System.String"/> 值。
/// </summary>
/// <param name="table"></param>
/// <param name="rowIndex">行所引</param>
/// <param name="colName">列名</param>
/// <returns></returns>
public static string FieldAt(this DataTable table, int rowIndex, string colName)
{
if (table.IsNullOrEmpty())
return string.Empty;

if (table.Rows.Count < rowIndex || (!table.Columns.Contains(colName)))
return string.Empty;
object o = null;

o
= table.Rows[rowIndex][colName];

return o == null ? string.Empty : o.ToString();
}
#endregion

/// <summary>
///<see cref="System.Data.DataTable"/> 对象以指定的方式遍历对象的 Rows(<see cref="System.Data.DataRow"/>) 属性并返回强类型 <see cref="System.Collections.Generic.List&lt;T&gt;"/> 结果集。
/// </summary>
/// <typeparam name="T">目标对象类型。</typeparam>
/// <param name="source">System.Data.DataTable 查询结果</param>
/// <param name="resultSelector">指定的方式,用于给强类型对象结果集指定添加方式。</param>
/// <returns></returns>
public static List<T> ToList<T>(this DataTable source, Func<DataRow, T> resultSelector)
{
if (source == null || source.Rows.Count == 0)
return null;
int count = source.Rows.Count;


List
<T> result = new List<T>(count);
if (resultSelector != null)
{
for (int i = 0; i < count; i++)
{
result.Add(resultSelector(source.Rows[i]));
}
}
return result;
}

        /// <summary>
        /// 返回  <see cref="System.Data.DataTable"/> 对象到强类型 <see cref="System.Collections.Generic.List&lt;T&gt;"/> <typeparamref name="T"/> 序列。
        /// </summary>
        /// <typeparam name="T">指定转换的强类型 </typeparam>
        /// <param name="source"><see cref="System.Data.DataTable"/> 对象,源。</param>
        /// <returns></returns>
        public static List<T> ToList<T>(this DataTable source) where T : class ,new()
        {
            if (source == null || source.Rows.Count == 0)
                return null;

            //Get all Columns of DataTable instance
            var cols = source.Columns.OfType<DataColumn>().Select(p => p.ColumnName).OrderBy(p => p).ToList();
            //Get All Properties of the T 
            Type t = typeof(T);
            var props = t.GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public).Select(o => o.Name).Where(p => cols.Contains(p)).ToList();

            int count = props.Count();
            int rows = source.Rows.Count;

            List<T> result = new List<T>(rows);
            for (int row = 0; row < rows; row++)
            {
                T entity = new T();

                for (int i = 0; i < count; i++)
                {
                    string prop = props[i];//属性名
                    t.GetProperty(prop).SetValue(entity, source.Rows[row][prop], null);
                    //快速反射调用..方式
                    //Common.DataUtils.SetPropertyValue(t, entity, prop, source.Rows[row][prop]);
                }
                result.Add(entity);
            }
            return result;
        }



/// <summary>
/// 返回 <see cref="System.Data.DataTable"/> 第一行第一列对应到 <typeparamref name="T"/> 类型的对象。如果当前 <see cref="System.Data.DataTable"/> 不包含数据据,则返回默认值。
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="source">The source.</param>
/// <returns></returns>
public static T FirstOrDefault<T>(this DataTable source) where T : class ,new()
{
return source.ToList<T>().FirstOrDefault();
}

/// <summary>
/// 对当前 <see cref="System.Data.DataTable"/> 对象数据进行分页,返回指定页起始索引,页大小的 <see cref="System.Data.DataTable"/> 副本。
/// </summary>
/// <param name="source">数据源</param>
/// <param name="pageIndex">页起始索引</param>
/// <param name="pageSize">每页记录数.</param>
/// <param name="totalRecords">总共记录数</param>
/// <returns></returns>
public static DataTable ToPage(this DataTable source, int pageIndex, int pageSize, out int totalRecords)
{
if (source.IsNullOrEmpty())
{
totalRecords
= 0;
return null;
}
totalRecords
= source.Rows.Count;
int startRow = (pageIndex - 1) * pageSize;
int endRow = startRow + pageSize;
if (startRow > totalRecords || startRow < 0)
{
startRow
= 0; endRow = pageSize;
}
if (endRow > totalRecords + pageSize)
{
startRow
= totalRecords - pageSize; endRow = totalRecords;
}
DataTable dt2
= source.Clone();
for (int i = startRow; i < endRow; i++)
{
if (i >= totalRecords) break;
dt2.Rows.Add(source.Rows[i].ItemArray);
}
return dt2;
}

/// <summary>
/// 对当前 <see cref="System.Data.DataTable"/> 对象数据进行分页,返回 pageSize 数内数量的 <typeparamref name="T"/> 类型序列。当前不包含数据则返回 NULL。
/// </summary>
/// <typeparam name="T">返回的<typeparamref name="T"/> 类型</typeparam>
/// <param name="source">数据源</param>
/// <param name="pageIndex">页起始索引.</param>
/// <param name="pageSize">每页记录数.</param>
/// <param name="totalRecords">总共记录数</param>
/// <returns></returns>
public static List<T> ToPage<T>(this DataTable source, int pageIndex, int pageSize, out int totalRecords) where T : class,new()
{
return source.ToPage(pageIndex, pageSize, out totalRecords).ToList<T>();
}

/// <summary>
/// 对当前 <see cref="System.Data.DataTable"/> 数据集进行排序并返回指定的强类型序列。
/// </summary>
/// <param name="source"><see cref="System.Data.DataTable"/> 源.</param>
/// <param name="orderByExpression">针对数据的排序语句。</param>
/// <returns></returns>
public static List<T> OrderBy<T>(this DataTable source, string orderByExpression) where T : class, new()
{
return source.OrderBy(orderByExpression).ToList<T>();
}

/// <summary>
/// 返回经过指定排序语句排序之后的当前 <see cref="System.Data.DataTable"/> 数据集副本。
/// </summary>
/// <param name="source"><see cref="System.Data.DataTable"/> 源.</param>
/// <param name="orderByExpression">针对数据的排序语句。</param>
/// <returns></returns>
public static DataTable OrderBy(this DataTable source, string orderByExpression)
{
if (source == null)
return null;
source.DefaultView.Sort
= orderByExpression;
return source.DefaultView.ToTable();
}

/// <summary>
/// 返回当前 <see cref="System.Data.DataTable"/> 指定需要的列的副本。
/// </summary>
/// <param name="source"><see cref="System.Data.DataTable"/> 源.</param>
/// <param name="columnsToReturn">需要返回的并包含在当前 <see cref="System.Data.DataTable"/> 中的列。</param>
/// <returns></returns>
public static DataTable Select(this DataTable source, params string[] columnsToReturn)
{
if (source.IsNullOrEmpty())
return null;
return source.DefaultView.ToTable(false, columnsToReturn);
}


/// <summary>
/// 遍历当前 <see cref="System.Data.DataTable"/> 的所有行。
/// </summary>
/// <param name="source">当前 <see cref="System.Data.DataTable"/>对象 。</param>
/// <param name="repeatter">指定遍历的操作。</param>
public static DataTable ForEach(this DataTable source, Action<DataRow> repeatter)
{
if (source == null)
return null;//throw new NullReferenceException("source");

if (repeatter != null && source.Rows.Count > 0)
{
foreach (DataRow item in source.Rows)
{
repeatter(item);
}
}

return source;
}


/// <summary>
///<see cref="System.Data.DataTable"/> 对象的Rows进行按指定谓词筛选的操作,并返回筛选结果的新的一个 <see cref="System.Data.DataTable"/> 实例。
/// </summary>
/// <param name="table">当前 <see cref="System.Data.DataTable"/> 对象。</param>
/// <param name="match">对行自定义的筛选条件</param>
/// <returns></returns>
public static DataTable Where(this DataTable table, Func<DataRow, bool> match)
{
if (table == null || table.Rows.Count == 0)
return null;
var result
= table.AsEnumerable().Where(match);

if (result != null && table.Rows.Count > 0)
{
DataTable temp;
try
{
temp
= result.CopyToDataTable();
}
catch (System.InvalidOperationException)
{
temp
= null;
}
return temp;
}
return null;
}

/// <summary>
///<see cref="System.Data.DataTable"/> 对象的Rows进行按指定筛选语句筛选,并返回筛选结果的新的一个 <see cref="System.Data.DataTable"/> 实例。
/// </summary>
/// <param name="table">The table.</param>
/// <param name="rowFilter">结果选择语句(T-SQL)</param>
/// <returns></returns>
public static DataTable Where(this DataTable table, string rowFilter)
{
if (table.IsNullOrEmpty())
return null;
table.DefaultView.RowFilter
= rowFilter;
return table.DefaultView.ToTable();
}

#endregion

 

 

 以上方法我就不一一解释了..这些方法都有经过测试使用过..呵呵 ..献丑 了...

分页的方法 参考了熊哥的实现。

 

 

posted @ 2010-07-08 10:36  Rukai  阅读(711)  评论(4编辑  收藏  举报