LINQ to count Continues repeating elements (int) in an int array?

Here is the scenario of my question: I have an array, say:

{ 4, 1, 1, 3, 3, 2, 5, 3, 2, 2 }

The result should be something like this (array element => its counter):

4 => 1
1 => 2
3 => 2
2 => 1
5 => 1
3 => 1
2 => 2

I know that this can be achieved with help for loop.

But google'd a lot to make this possible using less strict lines of code using LINQ without success.

+5
source share
10 answers

, "LINQ-like" . , . , , . , .

static class Extensions {

  public static IEnumerable<Tuple<T, Int32>> ToRunLengths<T>(this IEnumerable<T> source) {
    using (var enumerator = source.GetEnumerator()) {
      // Empty input leads to empty output.
      if (!enumerator.MoveNext())
        yield break;

      // Retrieve first item of the sequence.
      var currentValue = enumerator.Current;
      var runLength = 1;

      // Iterate the remaining items in the sequence.
      while (enumerator.MoveNext()) {
        var value = enumerator.Current;
        if (!Equals(value, currentValue)) {
          // A new run is starting. Return the previous run.
          yield return Tuple.Create(currentValue, runLength);
          currentValue = value;
          runLength = 0;
        }
        runLength += 1;
      }

      // Return the last run.
      yield return Tuple.Create(currentValue, runLength);
    }
  }

}

, , . Object.Equals. , , IEqualityComparer<T>, , .

:

var numbers = new[] { 4, 1, 1, 3, 3, 2, 5, 3, 2, 2 };
var runLengths = numbers.ToRunLengths();

:

4 1 
1 2 
3 2 
2 1 
5 1 
3 1 
2 2 
+8

( , ...)

( ), , LINQ. , , Zip Aggregate, . foreach :

// Simplest way of building an empty list of an anonymous type...
var results = new[] { new { Value = 0, Count = 0 } }.Take(0).ToList();

// TODO: Handle empty arrays
int currentValue = array[0];
int currentCount = 1;

foreach (var value in array.Skip(1))
{
    if (currentValue != value)
    {
        results.Add(new { Value = currentValue, Count = currentCount });
        currentCount = 0;
        currentValue = value;
    }
    currentCount++;
}
// Handle tail, which we won't have emitted yet
results.Add(new { Value = currentValue, Count = currentCount });
+3

LINQ, (: ):

var data = new int[] { 4, 1, 1, 3, 3, 2, 5, 3, 2, 2 };
var result = data.Select ((item, index) =>
                        new
                        {
                            Key = item,
                            Count = (index == 0 || data.ElementAt(index - 1) != item) 
                                ? data.Skip(index).TakeWhile (d => d == item).Count ()
                                : -1
                        }
                          )
                  .Where (d => d.Count != -1);

, , .

+3

?

public static IEnumerable<KeyValuePair<T, int>> Repeats<T>(
        this IEnumerable<T> source)
{
    int count = 0;
    T lastItem = source.First();

    foreach (var item in source)
    {
        if (Equals(item, lastItem))
        {
            count++;
        }
        else
        {
           yield return new KeyValuePair<T, int>(lastItem, count);
           lastItem = item;
           count = 1;
        }
    }

    yield return new KeyValuePair<T, int>(lastItem, count);
}

linq.

+2

, . .

foreach(var g in numbers.GroupContiguous(i => i))
{
  Console.WriteLine("{0} => {1}", g.Key, g.Count);
}
+1

Here (you can run this directly in LINQPad - rlewhere the magic happens):

var xs = new[] { 4, 1, 1, 3, 3, 2, 5, 3, 2, 2 };

var rle = Enumerable.Range(0, xs.Length)
                    .Where(i => i == 0 || xs[i - 1] != xs[i])
                    .Select(i => new { Key = xs[i], Count = xs.Skip(i).TakeWhile(x => x == xs[i]).Count() });

Console.WriteLine(rle);

Of course, this is O (n ^ 2), but you did not request linear efficiency in the specification.

+1
source
var array = new int[]{};//whatever ur array is
array.select((s)=>{return array.where((s2)=>{s == s2}).count();});

the only problem with tht, if you have 1 - two times, you will get the result for 1-two times

0
source
var array = new int[] {1,1,2,3,5,6,6 };
var arrayd = array.Distinct();
var arrayl= arrayd.Select(s => { return array.Where(s2 => s2 == s).Count(); }).ToArray();

Output

arrayl=[0]2 [1]1 [2]1 [3]1 [4]2
0
source
var array = new int[] {1,1,2,3,5,6,6 };
foreach (var g in array.GroupBy(i => i))
{
    Console.WriteLine("{0} => {1}", g.Key, g.Count());
}
0
source

Try GroupBythroughList<int>

        List<int> list = new List<int>() { 4, 1, 1, 3, 3, 2, 5, 3, 2, 2 };
        var res = list.GroupBy(val => val);
        foreach (var v in res)
        {
            MessageBox.Show(v.Key.ToString() + "=>" + v.Count().ToString());
        }
-4
source

All Articles