Home > Software engineering >  Merging String Lists
Merging String Lists

Time:11-14

guys.

I have three string lists like that:

list1         list2         list3
[0]xxx25,     [0]48,yyy     [0]95,www
[1]xxx36,     [1]25,yyy     [1]75,www
[2]xxx95,                   [2]36,www
[3]xxx48,        
[4]xxx75,

I want to end up with list1 like that:

list1
[0]xxx25,yyy
[1]xxx36,www
[2]xxx95,www
[3]xxx48,yyy
[4]xxx75,www

What's the best way to do this?

CodePudding user response:

well, I don't really understand how you structure your lists, but you could do something like that :

foreach(string line in list1)
{
   string indice = line.Replace("xxx","");//sets which index you are looking for (i.e "25,")
   bool indiceFound=false;
   foreach(string line2 in list2)
   {
      if(line2.StartsWith(indice))//if index is found
      {
         string stringToAdd = line2.Replace(indice,"");//set what to add to the line
         line =stringToAdd;//then add it to the original line
         indiceFound=true;//indicate you found it, so you don't nees to look in list3
         break;
      }
   }
   if(!indiceFound)
   {
      foreach(string line3 in list3)
      {
         if(line3.StartsWith(indice))
         {
            string stringToAdd = line3.Replace(indice,"");
            line =stringToAdd;
            break;
         }
      }
   }
}

CodePudding user response:

I built a solution that would use dictionaries. In the end, from my POV, it's all about defining the dictionaries that you will need to use to define your final list.

private static List<string> GetMergedArrays(List<string> list1, List<string> list2, List<string> list3)
{
    var dict1 = list1.ToDictionary(key => key.Substring(3), e => e);
    var dict2 = list2.ToDictionary(key => key.Split(",")[0], e => e.Split(",")[1]);
    var dict3 = list3.ToDictionary(key => key.Split(",")[0], e => e.Split(",")[1]);

    //Merge list2 and 3
    var dict2_3 = dict2.Concat(dict3).GroupBy(k => k.Key)
                                     .ToDictionary(x => x.Key, x => x.First().Value);

    var result = new List<string>();
    foreach (var item in dict1)
    {
        result.Add($"{item.Value},{dict2_3[item.Key]}");
    }
    return result;
}

Here is the Fiddle: https://dotnetfiddle.net/XusbnD

  • Related