我是linq查询的新手,请帮助解决此问题, dataset包含字段:
名称值Client_owner。
我想在name == "searchtext"
DataTable results = (from d in ((DataSet)_MyDataset).Tables["Records"].AsEnumerable()
orderby d.Field<string>("Name") ascending
where d["Name"].ToString().ToLower().Contains(ProjectName.ToLower())
select d??).CopyToDataTable();
答案 0 :(得分:4)
var query = (from d in _MyDataset.Tables["Records"].AsEnumerable()
where d.Field<String>("Name").Equals("searchText", StringComparison.CurrentCultureIgnoreCase)
select d).OrderBy(x => x.Field<String>("Name"));
if (query.Count() != 0) { DataTable result = query.CopyToDataTable(); }
如果_MyDataSet是DataSet对象,那么在您的示例中不需要额外的强制转换。
然后创建一个扩展方法来创建过滤数据表:
public static class DataTableExtensions
{
public static DataTable ReturnColumn(this DataTable dataTable, ICollection<String> fieldNames)
{
if (fieldNames.Count > 0)
{
for (int i = 0; i < dataTable.Columns.Count; i++)
{
DataColumn col = dataTable.Columns[i];
if (!fieldNames.Contains(col.ColumnName))
{
dataTable.Columns.Remove(col);
i--;
}
}
}
return dataTable;
}
}
然后您可以像这样过滤数据表:
results.ReturnColumn(new List<String> { "Value" });
将返回仅包含“Value”列的数据表
答案 1 :(得分:0)
如果你想返回一个“值”列表,你可以这样做:
IList<String> results = (_MyDataset.Tables["Records"].AsEnumerable().Where(
d => d.Field<String>("Name").Equals("searchText", StringComparison.CurrentCultureIgnoreCase)).Select(
d => d.Field<String>("Value")).OrderBy(x => x).ToList<String>());
答案 2 :(得分:0)
获得您希望它执行此类操作的最简单方法:
DataTable newDataTable = new DataTable("filteredTable");
Func<DataTable, String[], DataRow, DataRow> NewRow = delegate(DataTable targetTable, String[] columns, DataRow srcRow)
{
if (targetTable == null)
throw new ArgumentNullException("targetTable");
if (columns == null)
throw new ArgumentNullException("columns");
if (srcRow == null) throw new ArgumentNullException("srcRow");
if (columns.Count() == 0) throw new ArgumentNullException("srcRow");
DataRow row = targetTable.NewRow();
foreach (var column in columns)
{
if (!targetTable.Columns.Contains(column))
targetTable.Columns.Add(column);
row[column] = srcRow[column];
}
return row;
};
var query = (from d in _MyDataset.Tables["Records"].AsEnumerable()
where d.Field<String>("Name").Equals("searchText", StringComparison.CurrentCultureIgnoreCase)
select NewRow(newDataTable, new[] { "Value" }, d));
if (query.Count() != 0) { DataTable result = query.CopyToDataTable(); }
只有LINQ才能做到这一点