jkl jkl - 3 months ago 22
C# Question

Join multiple list on property in parallel

I would like to join multiple list with same type on property in parallel.
Let say I have three list like below.

List 1

id |Name |Phone|Address
1 |John |NULL |NULL
2 |David |NULL |NULL


List 2

id |Name |Phone|Address
1 |NULL |1234 |NULL
2 |NULL |5678 |NULL


List 3

id|Name|Phone|Address
1 |NULL|NULL |Plant ave
2 |NULL|NULL |Earth ave


I want to join three tables on ID in to a new list like,

New List

id|Name |Phone|Address
1 |John |1234 |Plant ave
2 |David|5678 |Earth ave


This is what I got so far,
lists.AsParallel().ForEach(JoinLists)
but I can't go further.

Any advice is appreciated.

Edit

This is what I did to join list. Not parallel.

var newList = from l1 in list1
join l2 in list2 on l1.Id equals l2.Id
join l3 in list3 on l1.Id equals l3.Id
select new
{
Id= l1.Id,
Name= li.Name,
Phone= l2.Phone,
Address = l3.Address
};

Answer

It sounds like you just want to parallelize your existing join. That's as simple as adding .AsParallel() to each source:

var newList = from l1 in list1.AsParallel()
              join l2 in list2.AsParallel() on l1.Id equals l2.Id
              join l3 in list3.AsParallel() on l1.Id equals l3.Id
              select new 
              {
                  Id= l1.Id,
                  Name= li.Name,
                  Phone= l2.Phone,
                  Address = l3.Address 
              };

As usual, you shouldn't assume anything about the ordering of the results - but if you don't care about that, this should be faster on suitable hardware. (It will be slightly less efficient overall though, of course. It still needs to do the same work, with added overhead for parallelization.)

Comments