1

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?

1
  • you can make it myDataTable.Rows.GroupBy(..) or myDataTable.AsEnumerable().GroupBy(..) Commented Aug 27, 2015 at 13:40

2 Answers 2

2

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()
                                });
Sign up to request clarification or add additional context in comments.

Comments

0

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());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.