0

I've got a list of List<KeyValuePair<string,string>>

var results = new List <KeyValuePair<string, string>>();

I've also got two Lists of strings:

var position= new List<string>{ "first", "second", "third" };
 
var name = new List<string>{ "John", "Diana", "Matthew", "Lisa", "James"};

The two lists can be of a different size, just would add an empty string instead.

I want to merge them together to create a new results. I'm currently using this:

 results = position.Zip(name, (x, y) => new KeyValuePair<string, string>(x, y)).ToList(); 

This would work if only both lists are of the same size. However, if not, its trimming the name list to match the position list. So not all values are there.

I need to achieve the following

first,John
second,Diana
third, Matthew
     , Lisa
     , Jame

Both lists can be, at any time, of variable sizes, not fixed. So sometimes name can be greater than position and vice versa.

I've seen were SelectMany is used, but not sure how to combine it to my Zip. Any ideas or suggestions?

Mezo
  • 85
  • 6
  • 1
    When you say "The two lists can be of a different size", can either be longer or just `name` longer than `position`? – Camilo Terevinto Aug 24 '20 at 18:32
  • Yes that is correct, both lists can be, at any time, of variable sizes. Not fixed. So sometimes `name` can be greater than `position` and vice versa. – Mezo Aug 24 '20 at 18:35

2 Answers2

0

I would increase the length of the name list to match the number of elements in position, adding empty strings as needed.

position.Zip(name.Concat(Enumerable.Repeat(string.Empty, Math.Max(0, position.Count - name.Count))), (x, y) => ...
ScottyD0nt
  • 348
  • 2
  • 8
  • in the subtraction would there be a resutl of -1? If so would that affect? Because both lists can be of variable sizes, they are not fixed. – Mezo Aug 24 '20 at 18:34
0

There's many ways of doing this. For example, a DIY one liner would be:

var position = // positions here
var name = // names here

var results = name
    .Select((n, nIdx) => new KeyValuePair(nIdx >= position.Length ? null : position[nIdx], n))
    .Concat(position.Skip(name.Length).Select(p => new KeyValuePair(p, (string)null))))
    .ToList(); 

Edited to allow either list to be larger.

Blindy
  • 65,249
  • 10
  • 91
  • 131