Newbie
Newbie

Reputation: 1111

Filter condition not working properly on list (C#3.0)

I have a datatable that has many NULL or " " strings. Next I am type casting the DataTable to a list . Now if I want to filter those conditions on this list and get the resultant value(without NULL or String.Empty or " " records) what should I do?

My code

DataTableExtensions.AsEnumerable(dt).ToList().ForEach(i =>
                {
                    if (i[0] != null)
                    {
                        if ((i[0].ToString() != string.Empty)|| (i[0].ToString() != " "))
                        {
                            list = dt.AsEnumerable().ToList();
                        }
                    }

                });

But I am getting all the records. It is not getting filtered.

Using C#3.0

Please help Thanks

Upvotes: 0

Views: 238

Answers (1)

Matt Hamilton
Matt Hamilton

Reputation: 204199

You're looking at i[0] so I'm going to assume that you're only interested in the first column of your table:

var rows = dt.AsEnumerable()
             .Where(r => !r.IsNull(0) // check for DBNull
                 && r[0] != null 
                 && r[0].ToString().Trim().Length > 0)
             .ToList();

So that looks at every row but only returns the rows where the first column has a value and the string value is not empty or whitespace.

Upvotes: 2

Related Questions