public static datatable todatatable(this ienumerable varlist)
{
datatable dtreturn = new datatable();
// column names
propertyinfo[] oprops = null;
if (varlist == null) return dtreturn;
foreach (t rec in varlist)
{
// use reflection to get property names, to create table, only first time, others will follow
if (oprops == null)
{
oprops = ((type) rec.gettype()).getproperties();
foreach (propertyinfo pi in oprops)
{
type coltype = pi.propertytype;
if ((coltype.isgenerictype) && (coltype.getgenerictypedefinition() == typeof (nullable<>)))
{
coltype = coltype.getgenericarguments()[0];
}
dtreturn.columns.add(new datacolumn(pi.name, coltype));
}
}
datarow dr = dtreturn.newrow();
foreach (propertyinfo pi in oprops)
{
dr[pi.name] = pi.getvalue(rec, null) == null ? dbnull.value : pi.getvalue
(rec, null);
}
dtreturn.rows.add(dr);
}
return dtreturn;
}
5 setallvalues 给数组中的每个元素赋值
实现给数组中的每个元素赋相同的值。
public static t[] setallvalues(this t[] array, t value)
{
for (int i = 0; i < array.length; i )
{
array[i] = value;
}
return array;
}
6 toxml 序列化对象为xml格式
可以将一个对象序列化为xml格式的字符串,保存对象的状态。
public static string toxml(this t o) where t : new()
{
string retval;
using (var ms = new memorystream())
{
var xs = new xmlserializer(typeof (t));
xs.serialize(ms, o);
ms.flush();
ms.position = 0;
var sr = new streamreader(ms);
retval = sr.readtoend();
}
return retval;
}
7 between 值范围比较
可以判断一个值是否落在区间范围值中。
public static bool between(this t me, t lower, t upper) where t : icomparable
{
return me.compareto(lower) >= 0 && me.compareto(upper) < 0;
}
类似这样的操作,下面的方法是取2个值的最大值。
public static t max(t value1, t value2) where t : icomparable
{
return value1.compareto(value2) > 0 ? value1 : value2;
}