4

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.

0

3 Answers 3

8

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I didn't know about lookups, that's great! Though I still need to have a list of lists, because it's being set to as a DataContext for a chart.
1

You need just GroupBy + ToList(one one the group itself an one on the whole thing):

List<List<Entry>> entriesByID = entries.GroupBy(entry => entry.ID)
            .Select(g => g.ToList())
            .ToList();

Comments

0

You could also do this:(Non-LINQ)

Dictionary<int , List<Entry>> dictionary = new ...

foreach (var v in entries)
    dictionary[v.ID].Add(v);

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.