Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert object collection to dictionary using LINQ

Tags:

c#

.net

linq

I have the following List of object collection.

column1:
Point data type
x=10,y=20

I have filtered that Point column using linq ofType<Point>.

Var XYLocations = Source.Select(g => g.ofType<Point>).ToList();

Now XYLocations contains duplicates.

From that list, I want to use linq to convert the list to dictionary<Point,List<int>> in which point is the key key and the corresponding matching row indixes act as values.

like image 888
Suresh Avatar asked Oct 28 '25 05:10

Suresh


1 Answers

Try something like this:

var xyLocations = //initialization
var dictionary = xyLocations
                     .Select((p, i) => new Tuple<Point, int>(p, i))
                     .GroupBy(tp => tp.Item1, tp => tp.Item2)
                     .ToDictionary(gr => gr.Key, gr => gr.ToList());

If you don't have Tuple you can use anonymous type instead:

var dictionary = xyLocations
                     .Select((p, i) => new {Item1 = p, Item2 = i})
                     .GroupBy(tp => tp.Item1, tp => tp.Item2)
                     .ToDictionary(gr => gr.Key, gr => gr.ToList());
like image 163
default locale Avatar answered Oct 30 '25 22:10

default locale