转载:c# Linq操作DataTable_lcawen的专栏-CSDN博客在平时的工作中,可能有很多情况下要对DataTable的里面的数据进行处理,最简单的例子如:对DataTable中的某个字段进行排序,根据条件筛选DataTable中的数据。。。,例子很多,下面我们看看如何处理的: 这是我最初写的代码: 代码 public static IEnumerable getEnumerable() { Datahttps://blog.csdn.net/lcawen88/article/details/8640724
首先:添加引用
项目添加引用 System.Data.DataSetExtensions
注意下面代码 AsEnumerable()方法的使用
代码一
public static IEnumerable getEnumerable()
{
DataTable dt = getDatatable();
try
{
var query = from q in dt.AsEnumerable()
where q.Field < string > ( " IPLocation " ) == " 北京 "
select new
{
IPid = q.Field < int > ( " IPid " ),
IPFrom = q.Field < string > ( " IPFrom " ),
IPTo = q.Field < string > ( " IPTo " ),
IPCity = q.Field < string > ( " IPCity " ),
IPToNumber = q.Field < string > ( " IPToNumber " ),
IPFromNumber = q.Field < string > ( " IPFromNumber " )
};
return query;
}
catch
{
return null ;
}
}
还可以这样:代码二
public static IEnumerable getEnumerable()
{DataTable dt = getDatatable();try{var query = from q in dt.AsEnumerable()orderby long .Parse(q[ " IPid " ].ToString()) descendingwhere q[ " IPid " ].ToString() == " 345058 "select new{IPid = q[ " IPid " ].ToString(),IPFrom = q[ " IPFrom " ].ToString(),IPTo = q[ " IPTo " ].ToString(),IPLocation = q[ " IPLocation " ].ToString(),IPCity = q[ " IPCity " ].ToString(),IPToNumber = q[ " IPToNumber " ].ToString(),IPFromNumber = q[ " IPFromNumber " ].ToString()};return query;// List<IPInfo> list = new List<IPInfo>();// foreach (var q in query)// {// IPInfo model = new IPInfo();// model.IPCity = q.IPCity;// model.IPFrom = q.IPFrom;// model.IPFromNumber = q.IPFromNumber;// model.IPid = long.Parse(q.IPid);// model.IPLocation = q.IPLocation;// model.IPTo = q.IPTo;// model.IPToNumber = q.IPToNumber;// list.Add(model);// }// return list;}catch{return null ;}
}