使用Linq从DataTable中删除列和行 [英] removing column and rows from DataTable using Linq

查看:308
本文介绍了使用Linq从DataTable中删除列和行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个DataTable作为输入,其中包含许多列和行,

I have a DataTable as an input which contains many columns and rows,

这是一个示例表:

我只想获取天气列(晴天行)和播放列(任何值)

I want get only the column Weather(sunny rows) with the column Play (any value)

所以输出可以是另一个这样的DataTable:

so the output can be another DataTable like this:

所以任何想法对我都有很大帮助,谢谢:)

So any idea can help me a lot, thank you :)

推荐答案

结果是否必须包含另一个DataTable?我只是使用命名或匿名类型.

Does the result has to another DataTable? I'd simply use a named or anonymous type.

var filtered = sourceTable.Rows.Cast<DataRow>()
.Where(x => x.Field<string>("WEATHER") == "sunny")
.Select(x => new
{
    Weather = x.Field<string>("WEATHER"),
    Play = x.Field<string>("PLAY")
})
.ToList();

然后您可以将其用作

foreach (var item in filtered)
{
    Console.WriteLine(string.Format("Weather ={0}, Play = {1}", item.Weather,item.Play));
}

如果需要结果为DataTable,则可以创建一个并手动添加行.

If you need the result to beDataTable, you can create one and add the rows manually.

这篇关于使用Linq从DataTable中删除列和行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆