How to get the range index of repeated elements. LINQ

Mansour_Dalir 1,611 Reputation points
2024-04-21T16:51:14.6766667+00:00

Thank

Dim MyArray as String()={"A","A","A","B","B","C","A","A"}

'Need Result as Array

0-2

3-4

5-5

6-7

VB
VB
An object-oriented programming language developed by Microsoft that is implemented on the .NET Framework. Previously known as Visual Basic .NET.
2,591 questions
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 112.8K Reputation points
    2024-04-21T19:10:55.76+00:00

    If LINQ is required:

    Dim MyArray As String() = {"A", "A", "A", "B", "B", "C", "A", "A"}
    
    Dim result As String() = MyArray.
        Select(Function(v, i) New With {v, i}).
        GroupBy(Function(p) p.v).
        SelectMany(Function(g) g.Select(Function(p, i) New With {p.v, p.i, .d = p.i - i})).
        GroupBy(Function(z) New With {Key z.v, Key z.d}).
        Select(Function(g) New With {g.Key.v, .min = g.Min(Function(b) b.i), .max = g.Max(Function(b) b.i)}).
        OrderBy(Function(t) t.min).
        Select(Function(t) $"{t.min}-{t.max}").
        ToArray
    

    The result is an array of strings like "0-2", "3-4", etc.

    1 person found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. Azar 19,410 Reputation points
    2024-04-21T18:51:23.11+00:00

    Hi there Mansour_Dalir

    Thats a good question and thanks for using QandA platform.

    try this code below

    using System;
    using System.Linq;
    using System.Collections.Generic;
    class Program
    {
        static void Main()
        {
            string[] myArray = { "A", "A", "A", "B", "B", "C", "A", "A" };
            var result = GetRangeIndexes(myArray);
            foreach (var range in result)
            {
                Console.WriteLine($"{range.Item1}-{range.Item2}");
            }
        }
        static List<Tuple<int, int>> GetRangeIndexes(string[] array)
        {
            var result = new List<Tuple<int, int>>();
            int start = 0;
            int end = 0;
            for (int i = 1; i < array.Length; i++)
            {
                if (array[i] == array[i - 1])
                {
                    end = i;
                }
                else
                {
                    result.Add(new Tuple<int, int>(start, end));
                    start = i;
                    end = i;
                }
            }
        
            result.Add(new Tuple<int, int>(start, end));
            return result;
        }
    }
    
    
    

    If this helps kindly accept the answer thank much.

    0 comments No comments