joelforsyth
joelforsyth

Reputation: 1041

Build custom objects from DataTable using LINQ

I'm trying to loop through data to build a list of objects that each has a list of objects. Here's what the data looks like

AccountID    AccountName    ListItem
------------------------------------
1            Foo            Item1
1            Foo            Item2
2            Test           Value1
2            Test           Value2
2            Test           Value3
3            Bar            List1
3            Bar            List2
3            Bar            List3

The other posts I've seen didn't quite tackle my issue. From my data, I would expect to create 3 Account objects, each having a List<string> of the ListItem data.

I was hoping to do something like this:

var accountGroups = myDataTable.GroupBy(x=>x.Field<string>("AccountName"));

and then loop through accountGroups to add the ListItems, but of course DataTable doesn't implement IEnumerable<T>

Is this possible with LINQ or should I just write the loop manually?

Upvotes: 1

Views: 1481

Answers (2)

D Stanley
D Stanley

Reputation: 152644

DataTable doesn't implement IEnumerable<T>

Not directly, but there's an AsEnumerable() extension method in System.Data.DataRowExtensions that will turn it into an IEnumerable<DataRow>.

var accountGroups = myDataTable.AsEnumerable()
                               .GroupBy(x=>x.Field<string>("AccountName"))
                               .Select(g => new Account {
                                    AccountName = g.Key,
                                    List = g.Select(g => g.Field<string>("ListItem").ToList()
                                });

Upvotes: 2

Tim Schmelter
Tim Schmelter

Reputation: 460360

but of course DataTable doesn't implement IEnumerable

You can use the extension method AsEnumerable:

IEnumerable<List<string>> accountListItems = myDataTable.AsEnumerable()
    .GroupBy(row => row.Field<string>("AccountName"))
    .Select(g => g.Select(row => row.Field<string>("ListItem")).ToList());

Upvotes: 0

Related Questions