Question

Suppose a List of strings List<string> lst_fruits contains the following elements:

[1] apple
[2] peach
[3] pine
[4] apple
[5] pear
[6] ...

I am looking for an existing method that does the task of combining #3 and #4.

I have considered copying the content of #4 into #3 and remove at #4, but I am wondering if there is a better solution.

Was it helpful?

Solution 2

Finally, I went with this:

public static List<string> combine_list_elements(List<string> lst_original, int i, int j)
{
   if (lst_original.Count > i && lst_original.Count > j)
   {
       lst_original[i] += " " + lst_original[j];
       lst_original.RemoveAt(j);
   }
   else
   {
       throw new Exception("One of these 2 items does not exist in this list.");
   }
   return lst_original;
}

It's simple enough, not sure why I was looking for else.

OTHER TIPS

Are you happy with this approach?

lst_fruits =
    lst_fruits
        .Take(2)
        .Concat(new []
        {
            String.Join("", lst_fruits.Skip(2).Take(2))
        })
        .Concat(lst_fruits.Skip(4))
        .ToList();
    lst_fruits[2] = string.Concat(lst_fruits[2], " ", lst_fruits[3]);
    lst_fruits.RemoveAt(3);

The list indexes in your example should start at zero, also. This is the simplest way to handle this, even though you seem to be looking for a more complicated option : )

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top