简体   繁体   中英

removing column and rows from DataTable using Linq

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

this is a sample table:

输入

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

so the output can be another DataTable like this:

产量

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

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();

Then you can use it as

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

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

If it's ok to get an anonymous list you can do like this:

var result = dt.AsEnumerable()
               .Where(x => x["WEATHER"] == "sunny")
               .Select(x => 
                     new 
                        { 
                            WEATHER = x["WEATHER"] as string, 
                            PLAY = x["PLAY"] as string 
                        });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM