Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a Multidimensional array from a list of objects

Tags:

c#

.net

linq

I have a list of "Entry" objects (that each have an ID), and want to create a 2D array based by splitting them up by ID:

class Entry
{
    public int ID { get; set; }
    public int value { get; set; }

    public Entry(int id, int value)
    {
        this.ID = id;
        this.value = value;
    }
}

Population:

        List<Entry> entries = new List<Entry>();
        entries.Add(new Entry(0, 20));
        entries.Add(new Entry(1, 20));
        entries.Add(new Entry(1, 25));
        entries.Add(new Entry(2, 21));
        entries.Add(new Entry(2, 23));

I need to build a Multidimensional list of entries split up by ID. The following code builds the array:

        List<Entry> entriesZero = new List<Entry>();
        entriesZero.Add(new Entry(0, 20));

        List<Entry> entriesOne = new List<Entry>();
        entriesOne.Add(new Entry(1, 20));
        entriesOne.Add(new Entry(1, 25));

        List<Entry> entriesTwo = new List<Entry>();
        entriesTwo.Add(new Entry(2, 21));
        entriesTwo.Add(new Entry(2, 23));

        List<List<Entry>> entriesByID = new List<List<Entry>>();
        entriesByID.Add(entriesZero);
        entriesByID.Add(entriesOne);
        entriesByID.Add(entriesTwo);

What would be the best way to accomplish something like this? I could do it with multiple foreach loops but I'm wondering if there's a better way in LINQ.

like image 291
David Avatar asked Jan 14 '23 21:01

David


1 Answers

Do you definitely need it to be a list grouped by ID? A Lookup will do this for you really easily:

ILookup<int, Entry> entriesById = entries.ToLookup(e => e.Id);

You can still iterate over that, but you can also look up all the entries for any ID.

If you really, really need a List<List<Entry>> you could do this:

var listOfLists = entriesById.GroupBy(e => e.Id)
                             .Select(g => g.ToList())
                             .ToList();

... but I'd go with the lookup.

like image 189
Jon Skeet Avatar answered Jan 16 '23 11:01

Jon Skeet