Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

LINQ query .ToDictionary with Tuple int key

I’m wondering if is it possible to do a linq query like this:

Dictionary<(int,int), object)> entity = _context.Table.ToDictionary((i => i.IDOrigin, i.IDDestiny), o => o);

I know that it’s possible with an unique key .ToDictionay(i => i.Key, o => o.Value); but in this case this table has a double PK and I need both as keys.

Thank you.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You just need to tweak your call a bit:

_context.Table.ToDictionary(i => (i.IDOrigin, i.IDDestiny), o => o)

All I’ve moved is the brackets: you still want i as a regular lambda expression parameter, but you want the result of the lambda to be a tuple literal, which is the (i.IDOrigin, i.IDDestiny) part.

Note that the o => o part is unnecessary – if you don’t specify a lambda expression for projecting from a source element to a value, ToDictionary uses the source element as the value. So you can use:

_context.Table.ToDictionary(i => (i.IDOrigin, i.IDDestiny))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading