borgesgj
borgesgj

Reputation: 45

LINQ Convert List of items to Lookup of rows with redundant values

I believe the title doesn't help much, I'll try to explain better here... and hopefully you can help me.

I have this class

public class ItemValue
{
    public string SetId {get; set;}
    public string ItemId {get; set;}
    public string Value {get; set;}
}

And I have a collection of objects of this class like this one

IEnumerable<ItemValue> = new List<ItemValue>()
{
    new ItemValue
    {
        SetId = "S1",
        ItemId = "I1",
        Value = "S1I1V",
    },
    new ItemValue
    {
        SetId = "S1",
        ItemId = "I2",
        Value = "S1I2V",
    },
    new ItemValue
    {
        SetId = "S1",
        ItemId = "I3",
        Value = "S1I3V",
    },
    new ItemValue
    {
        SetId = "S2",
        ItemId = "I1",
        Value = "S2I1V",
    },
    new ItemValue
    {
        SetId = "S2",
        ItemId = "I2",
        Value = "S2I2V1",
    },
    new ItemValue
    {
        SetId = "S2",
        ItemId = "I2",
        Value = "S2I2V2",
    },
    new ItemValue
    {
        SetId = "S2",
        ItemId = "V3",
        Value = "S2I3V",
    }
};

Notice there are 2 instances with SetId="S2" and ItemId="I2" with different values

What I need is to map this collection to something like this using LINQ

var expectedResult = new Lookup<string, IDictionary<string, string>>()
{
    ["S1"] = new Dictionary<string, string>() 
    {
        { ["I1"] = "S1I1V" },
        { ["I2"] = "S1I2V" },
        { ["I3"] = "S1I3V" },
    },
    ["S2"] = new Dictionary<string, string>() 
    {
        { ["I1"] = "S2I1V" },
        { ["I2"] = "S2I2V1" },
        { ["I3"] = "S2I3V" },
    },
    ["S2"] = new Dictionary<string, string>() 
    {
        { ["I1"] = "S2I1V" },
        { ["I2"] = "S2I2V2" },
        { ["I3"] = "S2I3V" },
    }
};

I'm not good at LINQ myself and after some unsuccessful LINQ trials and an ugly solution using a bunch of foreach and ifs, I'm now reaching you to please get some ideas for this.

If you need any additional information, please just let me know

Thank you very much in advance!...

Upvotes: 1

Views: 168

Answers (1)

JonasH
JonasH

Reputation: 36361

you could do something similar with GroupBy and ToDictionary/ToLookup

        var dict = items.GroupBy(i => i.SetId)
            .ToDictionary(
                group => group.Key,
                group => group.ToLookup(i => i.ItemId, i => i.Value));
         dict["S2"]["I2"].ToList() // usage example

An alternative would be

var dict2 = items.ToLookup(i => (i.SetId, i.ItemId), i => i.Value);
dict2[("S2", "I2")].ToList() // usage example

Upvotes: 1

Related Questions