Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

zipping/merging two sorted lists

Tags:

c#

i have two sorted dictionaries both with the type signature

i.e.

SortedDictionary<decimal, long> A
SortedDictionary<decimal, long> B

I want to merge the two lists where the key is the same, thus creating a new list like

SortedDictionary<decimal, KeyValuePair<long,long>>
or
SortedDictionary<decimal, List<long>>

This may not be the best way of approacing the situation but could someone give me a heads up on how to do this or a better way to approach it.

like image 678
Abstract Avatar asked Apr 11 '12 12:04

Abstract


People also ask

How do I merge two linked lists?

(1) Create a new head pointer to an empty linked list. (2) Check the first value of both linked lists. (3) Whichever node from L1 or L2 is smaller, append it to the new list and move the pointer to the next node. (4) Continue this process until you reach the end of a linked list.

How do I merge two sorted arrays in ascending order?

Approach - 3 : Merge Sort In the merge sort approach of the merge sorted arrays problem, we merge elements of two input sorted arrays using the merge sort algorithm. In the merge sort, we traverse both input arrays simultaneously and apply a merge sort algorithm for getting sorted resultant arrays.


1 Answers

This is what I've got:

SortedDictionary<decimal, List<long>> merged = new SortedDictionary<decimal, List<long>>
 (
   A.Union(B)
   .ToLookup(x => x.Key, x => x.Value)
   .ToDictionary(x => x.Key, x => new List<long>(x))
 );

EDIT: Above solution selects keys not included in both collections. This should select where keys are same:

SortedDictionary<decimal, List<long>> merged = new SortedDictionary<decimal, List<long>>
 (
   A.Where(x=>B.ContainsKey(x.Key))
   .ToDictionary(x => x.Key, x => new List<long>(){x.Value, B[x.Key]})
 );
like image 184
Renatas M. Avatar answered Oct 11 '22 18:10

Renatas M.