codeandcloud
codeandcloud

Reputation: 55248

How to pull filtered Data from a Datatable and create a string

I have a dataset ds with two fields, AllowInput int and TypeName string.
I wanna get all TypeName as a comma separated string where AllowInput == 1

This is what I have done so far.

string keys = string.Join(",", ds.Tables[0].Rows.Cast<DataRow>().
                Where(x => x["AllowInput"].ToString() == "1").
                ToArray().
                Cast<DataRow>().
                Select(x => x["TypeName"].ToString()).
                ToArray());

This works. But does the code needs to be this verbose?

Upvotes: 1

Views: 112

Answers (2)

vc 74
vc 74

Reputation: 38179

You could also consider using the DataRow extensions defined in Linq to DataSet

Something like:

string keys = string.Join(",", from row in table.AsEnumerable()
                               where (row.Field<int>("AllowInput") == 1)
                               select row.Field<string>("TypeName"));

Upvotes: 1

leppie
leppie

Reputation: 117280

You can probably drop the following 2 lines:

            ToArray().
            Cast<DataRow>().

Upvotes: 2

Related Questions