Search code examples
c#blazorblazor-server-sideblazor-webassemblyasp.net-blazor

Join element from array if the array element length is less than 5


I am trying to join the next array element together to single element from array if the element of the array is less than length 4. It should add to the next element index.

Another logic is, if the next consecutive array length is also less then 4 char then it joins the next array element also up to 3 times in total. I want to implement this. It's getting complex for me I am not understand this logic.

This is the code, here it has array on titleList, now we have to use the above logic in this array list.

@foreach (var title in randomtitle)  
{
   </span>@titleList.ElementAt(title)</span>
}

@code {
    [Parameter]
    public string theTitle { get; set; }
    private string[] titleList = Array.Empty<string>();

    protected override void OnParametersSet()
    {  
        if (!string.IsNullOrEmpty(theTitle))
        {
            titleList = theTitle.Split(" ");
        }
    }

    private Random random = new();
    
    private IEnumerable<int> randomtitle =>
        Enumerable.Range(0, titleList.Count() - 1) // { 0, 1, 2, 3 } generate sequence
            .OrderBy(x => random.Next())      // { 3, 1, 0, 2 } random shuffle
            .Take(2)                          // { 3, 1 }       pick two
            .ToList();
}

Solution

  • I think you are looking for a method that does following:

    • take a collection of strings(like a string[])
    • iterate each string and check if it's length is greater than or equal 4
    • if so, everything is fine, take it as it is
    • if not, append the next to the current string and check their length afterwards
    • if they are still not greater than or equal 4 append the next one, but max 3 times

    Then this should work (not tested well though):

    Demo: https://dotnetfiddle.net/2uHREv

    static string[] MergeItems(IList<string> all, int minLength, int maxGroupCount)
    {
        List<string> list = new List<string>(all.Count);
        for(int i = 0; i < all.Count; i++)
        {
            string current = all[i];
            if(i == all.Count - 1)
            {
                list.Add(current);
                break;            
            }
    
            if (current.Length < minLength)
            {
                for (int ii = 1; ii < maxGroupCount && i + ii < all.Count; ii++)
                {
                    int nextIndex = i + ii;
                    string next = all[nextIndex];
                    current = current + next;
                    if (current.Length >= minLength || ii+1 == maxGroupCount)
                    {
                        list.Add(current);
                        i = nextIndex;
                        break;
                    }
                }
            }
            else
            {
                list.Add(current);
            }
        }
    
        return list.ToArray();
    }