Sandro Manzo Sandro Manzo - 4 years ago 114
C# Question

Linq : Checking how many times the same value consecutively

it's my first question so if it's not quite clear , you can ask for extra information. Keep in mind that english is not my native language :).

I was wondering if it's possible to have an elegant way for next specification.
I think linq could be a possibility but i haven't got enough experience with the technology to get it to work:).

Remark this is not a homework assignment it's just a way to get an new angle to solve these kind of problems.

I've tried with the aggegrate function, maybe an action could help.

I want to keep track of:


  • the max times a value occurs in an array consecutively.

  • Per value it should display the maximum times the value occured consecutively



for example:

we have an array of 6 elements with elements either 0 or 1

0 , 0 , 0 , 1 , 1 ,0 result : 3 times 0 , 2 times 1
0 , 0 , 1 , 1 , 1 ,0 result : 2 times 0 , 3 times 1
0 , 1 , 0 , 1 , 1 ,0 result : 1 time 0 , 2 times 1
0 , 0 , 1 , 1 , 0 ,0 result : 2 times 0 , 2 times 1


Thanks in advance

Answer Source

I don't think Linq being a good way out; but a simple method will do:

// Disclamer: Dictionary can't have null key; so source must not coтtain nulls
private static Dictionary<T, int> ConsequentCount<T>(IEnumerable<T> source) {
  if (null == source)
    throw new ArgumentNullException("source");

  Dictionary<T, int> result = new Dictionary<T, int>();

  int count = -1;
  T last = default(T);

  foreach (T item in source) {
    count = count < 0 || !object.Equals(last, item) ? 1 : count + 1;
    last = item;

    int v;

    if (!result.TryGetValue(last, out v))
      result.Add(last, count);
    else if (v < count)
      result[item] = count;
  }

  return result;
}

Tests:

  int[][] source = new int[][] { 
    new[] { 0, 0, 0, 1, 1, 0 },
    new[] { 0, 0, 1, 1, 1, 0 },
    new[] { 0, 1, 0, 1, 1, 0 },
    new[] { 0, 0, 1, 1, 0, 0 }, };

  string report = string.Join(Environment.NewLine, source
    .Select(array => $"{string.Join(" , ", array)} result : " + 
                         string.Join(", ", 
        ConsequentCount(array)
          .OrderBy(pair => pair.Key)
          .Select(pair => $"{pair.Value} times {pair.Key}"))));

  Console.Write(report);

Outcome:

0 , 0 , 0 , 1 , 1 , 0 result : 3 times 0, 2 times 1
0 , 0 , 1 , 1 , 1 , 0 result : 2 times 0, 3 times 1
0 , 1 , 0 , 1 , 1 , 0 result : 1 times 0, 2 times 1
0 , 0 , 1 , 1 , 0 , 0 result : 2 times 0, 2 times 1
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download