0

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

this is a sample table:

Input

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

so the output can be another DataTable like this:

Output

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

3
  • You strictly need a DataTable as a result? Why not a list? Commented May 10, 2015 at 12:32
  • I need tow columns as output, so list will contain what exactly ? Commented May 10, 2015 at 12:36
  • You can see my answer, you get a list with the values needed. Another DataTable would be really unuseful. Commented May 10, 2015 at 12:38

2 Answers 2

3

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 beDataTable, you can create one and add the rows manually.

Sign up to request clarification or add additional context in comments.

8 Comments

So if I want to do another Linq statements, it is okey to be done on the new list ?
I may need to do group by on the new list for example
@MBH Group by what column? You have only the filtered data in the list.
@MBH Yes. foreach (var groupped in filtered.GroupBy(x => x.Play)) {int groupCount = groupped.Count();}
I already answered your question. If you need more question ask another question please.
|
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.