0

I have a List(Of List(Of MyObject)). I have a method that returns a List(Of MyObject). I want to add each returned list to the list of lists. This is straightforward with LoL.Add(L). However, I want to be able to refer to each list by a key.

For example:

Key: "A"
    MyObject1
    MyObject2
Key: "B"
    MyObject3
    MyObject4
    MyObject5

I have read over a dozen questions similar to this issue: group a list of lists, group a list of objects into a list of lists, and grouping a list of objects into a new list of list of objects. I can't seem to adapt the code in the answers to my problem.

All the questions I've read seem to assume that the list of lists is good to go and not being made piecemeal. All my attempts end up with type conversion errors and exceptions.

I'm not sure if I should use IGrouping or a Dictionary object instead, but my attempts there also failed.

I tried reverse-engineering another piece of code I have, which works in a similar fashion:

Dim assignmentListByDay = _routeAssignments.OrderBy(Function(a) a.AssignmentDate).
    GroupBy(Function(a) a.AssignmentDate)

Here, _routeAssignments is of type IEnumerable(Of MyObject). assignmentListByDay becomes IEnumerable(Of IGrouping(Of Date, MyObject). Later in my code, I can do:

For Each assignmentList In assignmentListByDay

    Dim ucAssignment As New ucSingleDayAssignment With _
        {.AssignmentDate = assignmentList.Key,
         .Assignments = assignmentList.ToList}

    'do stuff

Next

I tried to do something similar by making my list of lists into a List(Of IGrouping(Of String, MyObject), but I can't figure out how to convert the returned list to IGrouping(Of String, MyObject) or if that's even the right approach.

Note that I'm free to change what is returned and the various types (List, IEnumberable, IGrouping, Dictionary), but I don't know which to use in this situation. Right now it seems like my best bet is to add each list to a list of lists or one giant list, then do the GroupBy. That doesn't seem terribly efficient, though.

In the end, my goal is to iterate over each group, then iterate over each list in that group.

Community
  • 1
  • 1
Zairja
  • 1,441
  • 12
  • 31

1 Answers1

2

A list of lists is not the right structure if you need a key. One choice would be a Dictionary (Of String, List(Of MyObject)).

Zairja
  • 1,441
  • 12
  • 31
D Stanley
  • 149,601
  • 11
  • 178
  • 240
  • I used this approach and got things working. I'd still like to know how to properly create and manipulate a `List(Of IGrouping...`. The documentation had an example slightly too esoteric (for me at least). I'll keep trying on that front and hopefully learn something new. If it works, I'll add it as an answer, as well. – Zairja May 19 '14 at 21:31