Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error in Conversion from Generic List<Datarow> to Generic List<string>

I have the code below

List<string> esfa = NewTable.AsEnumerable().Where(row => row.Field<string>("Select")   
=="true").ToList();

While compile getting error

Cannot implicitly convert type 'System.Collections.Generic.List<System.Data.Datarow>' to 'System.Collections.Generic.List<string>'

Please help.

like image 618
Rohit Avatar asked May 05 '26 06:05

Rohit


1 Answers

Well, yes. You're filtering by the Select field - but the result of that filtering is still a sequence of rows. I would expect that to be what you want - after all, you know the value of the Select field in every row, so that can't be interesting...

I think you probably just want:

List<DataRow> rows = NewTable.AsEnumerable()
                             .Where(row => row.Field<string>("Select") == "true")
                             .ToList();

(Note that breaking the code into multiple lines like this can greatly aid readability.)

If you actually wanted the value of some other field, you might want something like:

List<string> rows = NewTable.AsEnumerable()
                            .Where(row => row.Field<string>("Select") == "true")
                            .Select(row => row.Field<string>("LastName"))
                            .ToList();
like image 73
Jon Skeet Avatar answered May 08 '26 12:05

Jon Skeet