再写一个Linq使用实例:将DataTable变为强类型的数据表

如果你的数据源不是直接返回OO集合,而是过去常见的弱类型DataSet,那么也可以先把它用Linq管理起来,如下:

public static class ExtMethods
{
    public static IEnumerable<mySimpleType> Cast<MySimpleType>(this DataTable obj)
    {
        List<mySimpleType> ret = new List<mySimpleType>();
        foreach (DataRow row in obj.Rows)
            ret.Add(new mySimpleType() { Name = row["name"], Date = row["date"], Doc = row["doc"] });
        return ret;
    }
}

public class mySimpleType
{
    public string Name;
    public DateTime Date;
    public List<System.Xml.XmlDocument> Doc;
}

 



在主程序中,可以这样写查询了:

DataSet abc;
//todo: 设置abc的数据
var search = from r in abc.Tables["SimpleTable"].Cast<mySimpleType>()
             where r.Name.StartsWith("wu") && r.Date >= DateTime.Parse("2008/1/10")
             select r;

 



Linq起步是不是特别简单呢?!

posted @ 2013-04-11 11:11  C#老头子  Views(297)  Comments(0)    收藏  举报