user1477388
user1477388

Reputation: 21430

Getting a list of strings via LINQ

I am trying to get a list of a list of strings in the code below and I am getting an on select that reads:

Cannot implicitly convert type 'System.Data.EnumerableRowCollection>' to 'System.Collections.Generic.List>'

List<List<string>> rows = (from myRow in data.AsEnumerable()
                            select new List<string> {myRow["FirstName"].ToString(),
                                myRow["LastName"].ToString(),
                                myRow["Department"].ToString(),
                                myRow["Birthdate"].ToString(),
                                myRow["Description"].ToString()
                            });

How can I get a list of a list of strings?

Upvotes: 1

Views: 201

Answers (2)

Tim Schmelter
Tim Schmelter

Reputation: 460028

Method syntax is more concise:

List<List<string>> rows = data.AsEnumerable()
    .Select(r => r.ItemArray.Select(o => o + "").ToList())
    .ToList();

"half" query syntax:

rows = (from row in data.AsEnumerable()
        select row.ItemArray.Select(o => o + "").ToList())
       .ToList();

Upvotes: 2

Krumelur
Krumelur

Reputation: 33048

Linq is working with enumerables (IEnumerable). You need to convert to a list:

List<List<string>> rows = (from myRow in data.AsEnumerable()
                            select new List<string> {myRow["FirstName"].ToString(),
                                myRow["LastName"].ToString(),
                                myRow["Department"].ToString(),
                                myRow["Birthdate"].ToString(),
                                myRow["Description"].ToString()
                            }).ToList();

Upvotes: 5

Related Questions