Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flattening nested dictionaries with LINQ

Tags:

c#

linq

nested

So I have a dictionary of the form Dictionary<int, Dictionary<int, Object>> myObjects and I would like to flatten this to a List<Object> flattenedObjects as simply as possible. I tried to come up with a clever solution, but so far all I've gotten to work is a solution with two nested foreach -loops that iterate over all of the elements, but I suppose there should be a nicer way of accomplishing this with LINQ.

like image 311
bobblez Avatar asked Dec 07 '11 12:12

bobblez


People also ask

How to flatten a list using LINQ C #?

How to flatten a list using LINQ C#? Flattening a list means converting a List<List<T>> to List<T>. For example, let us consider a List<List<int>> which needs to be converted to List<int>. The SelectMany in LINQ is used to project each element of a sequence to an IEnumerable<T> and then flatten the resulting sequences into one sequence.

Why do you need a flattened dictionary in Python?

There are many reasons you would need a flattened dictionary. One is that it makes it simpler to compare two dicts. The other is that it’s easier to navigate and manipulate it, since a flat structure is one level deep. Python is a versatile language, meaning you can achieve the same goals in several ways.

What does it mean to flatten a list?

Flattening a list means converting a List<List<T>> to List<T>. For example, let us consider a List<List<int>> which needs to be converted to List<int>.

What is the use of selectmany in LINQ?

The SelectMany in LINQ is used to project each element of a sequence to an IEnumerable<T> and then flatten the resulting sequences into one sequence. That means the SelectMany operator combines the records from a sequence of results and then converts it into one result.


2 Answers

try this

List<Object> flattenedObjects = myObjects.Values.SelectMany(myObject => myObject.Values).ToList();
like image 70
Haris Hasan Avatar answered Sep 22 '22 10:09

Haris Hasan


Like this:

var result = myObjects.Values.SelectMany(d => d.Values).ToList();
like image 35
Klaus Byskov Pedersen Avatar answered Sep 22 '22 10:09

Klaus Byskov Pedersen