Newbie
Newbie

Reputation: 1111

Rewrite the foreach using lambda + C#3.0

I am tryingv the following

foreach (DataRow dr in dt.Rows)
                        {
                            if (dr["TABLE_NAME"].ToString().Contains(sheetName))
                            {
                                tableName = dr["TABLE_NAME"].ToString();
                            }
                        }

by using lambda like

string tableName = "";
                        DataTableExtensions.AsEnumerable(dt).ToList().ForEach(i =>
                            {
                                tableName = i["TABLE_NAME"].ToString().Contains(sheetName);
                            }
                        );

but getting compile time error "cannot implicitly bool to string". So how to achieve the same.?

Thanks(C#3.0)

Upvotes: 2

Views: 426

Answers (1)

Pratik Deoghare
Pratik Deoghare

Reputation: 37172

tableName is string and Contains() returns bool.

So the error is because of

    tableName = i["TABLE_NAME"].ToString().Contains(sheetName);

What you can do is (but I think better options are available in linq )

string tableName = "";
DataTableExtensions.AsEnumerable(dt).ToList().ForEach(i =>
    {
        var s =  i["TABLE_NAME"];
        if(s.ToString().Contains(sheetName))
            tableName = s;
    }
);

Best of luck.

Upvotes: 2

Related Questions