0

Is it possible to use LINQ to collaps/merge two or more collection of the same type and size into a new collection of same type and size ?

var list01 = new List<string> { "A",  "", "", "B",  "",  "", "" };
var list02 = new List<string> {  "", "C", "",  "",  "", "D", "" };
var list03 = new List<string> {  "",  "", "",  "", "E",  "", "" };

           The desired result:  "A", "C", "", "B", "E", "D", "";

If one collection holds data at a certain position, none of the other collections will hold data at the same position, for instance the first position in list02 and list03 will always be empty because list01 holds A in the first position.

ZeeLap
  • 13
  • 2
  • Possible duplicate of [How to combine more than two generic lists in C# Zip?](https://stackoverflow.com/questions/10297124/how-to-combine-more-than-two-generic-lists-in-c-sharp-zip) – Drag and Drop Aug 30 '18 at 08:40

3 Answers3

9

You probably want to use Zip twice:

var result = list01
                .Zip(list02, (a, b) => !string.IsNullOrEmpty(a) ? a : b)
                .Zip(list03, (a, b) => !string.IsNullOrEmpty(a) ? a : b);
Console.WriteLine(string.Join(",", result));

Try it online

ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86
3

Or an alternative solution, just add items together inside Zip:

var list = list01.Zip(list02, (a,b) => a + b)
                 .Zip(list03, (a,b) => a + b);

adding string to null or to empty string will give same result.

SᴇM
  • 7,024
  • 3
  • 24
  • 41
  • Though might give weird results if OP's assertion that there will always be a single item in that position is ever proved wrong. That being said, if that happens, mine might give unexpected results too. :-) – ProgrammingLlama Aug 30 '18 at 08:43
  • @John Yeap :-). – SᴇM Aug 30 '18 at 08:47
0

As other suggested, it can be achieved using some inbuilt functions of LINQ.

Following solution is without any inbuilt function.

static List<string> megreLists(List<string> lst1, List<string> lst2)
{
    List<string> result = new List<string>();

    if (lst1.Count == lst2.Count)
    {
        for (int i = 0; i < lst1.Count; i++)
        {
            if (string.IsNullOrWhitespace(lst1[i]) && lst1[i].Trim() == lst2[i].Trim())
            {
                result.Add(lst1[i]);
            }
            else if (string.IsNullOrWhitespace(lst1[i]) && lst1[i].Trim() != lst2[i].Trim())
            {
                result.Add(lst1[i]);
            }
            else if (string.IsNullOrWhitespace(lst2[i]) && lst1[i].Trim() != lst2[i].Trim())
            {
                result.Add(lst2[i]);
            }
        }
    }

    return result;
}



var result = megreLists(megreLists(list01, list02), list03);
Gaurang Dave
  • 3,956
  • 2
  • 15
  • 34