I have the following code which produces a dictionary containing multiple lists; each list can be retrieved with a numeric key.
public class myClass
{
public string Group { get; set; }
public int GroupIndex { get; set; }
...
}
public List<MyClass> myList { get; set; }
private Class IndexedGroup
{
public int Index { get; set; }
public IEnumerable<MyClass> Children { get; set; }
}
public Dictionary<int, IEnumerable<MyClass>> GetIndexedGroups(string group)
{
return myList.Where(a => a.Group == group)
.GroupBy(n => n.GroupIndex)
.Select(g => new IndexedGroup { Index = g.Key, Children = g })
.ToDictionary(key => key.Index, value => value.Children);
}
Is there any way to eliminate the IndexedGroup class?
I’ve tried using an anonymous type in the Select method, like this:
.Select(g => new { Index = g.Key, Children = g })
but I get a type conversion error.
You could just get rid of the
Select()entirely and call.AsEnumerable():Or you could change your return type to an
ILookup, which is basically the data structure you’re going for: