Reputation: 20464
I want to store the duplicated values of an Array, or what is the same I want to delete the Unique names.
For example if I have an Array with this content:
{a, b, c, c, c}
I want to store this in other array:
{c, c, c}
I know how to perform the operation using a For loop but I want to improve the code using LINQ extensions (if is possibly).
Upvotes: 0
Views: 181
Reputation: 2598
(In C#) this a much faster implementation then doing a GroupBy/Where/SelectMany (and a Count() that enumerates). But I must agree that it is more code ;-)
var array = new[] { 1, 2, 3, 3, 3 };
var valueCounter = new ValueCounter<int>(array);
var query = valueCounter.Where(p => p.Value > 1)
.SelectMany(p => Enumerable.Repeat(p.Key, p.Value)).ToArray();
Using this ValueCounter class:
public class ValueCounter<T> : IEnumerable<KeyValuePair<T, int>>
{
private readonly IEqualityComparer<T> _comparer;
private readonly Dictionary<T, int> _valueCounter;
private int _nullCount = 0;
public ValueCounter(IEnumerable<T> values, IEqualityComparer<T> comparer)
{
_comparer = comparer ?? EqualityComparer<T>.Default;
_valueCounter = new Dictionary<T, int>(_comparer);
if (values != null)
{
foreach (var value in values)
{
Add(value);
}
}
}
public ValueCounter(IEqualityComparer<T> comparer)
: this(null, comparer)
{
}
public ValueCounter(IEnumerable<T> values)
: this(values, null)
{
}
public ValueCounter()
: this(null, null)
{
}
public void Add(T value)
{
if (value == null)
{
_nullCount++;
}
else
{
int count;
if (_valueCounter.TryGetValue(value, out count))
{
_valueCounter[value] = count + 1;
}
else
{
_valueCounter.Add(value, 1);
}
}
}
/// <summary>
/// Removes a value
/// </summary>
/// <param name="value">The value that needs to be removed</param>
/// <returns>True if a value was removed</returns>
public bool Remove(T value)
{
if (value == null)
{
if (_nullCount > 0)
{
_nullCount--;
return true;
}
}
else
{
int count;
if (_valueCounter.TryGetValue(value, out count))
{
if (count == 1)
{
_valueCounter.Remove(value);
}
else
{
_valueCounter[value] = count - 1;
}
return true;
}
}
return false;
}
public int GetCount(T value)
{
int result;
_valueCounter.TryGetValue(value, out result);
return result;
}
public IEnumerator<KeyValuePair<T, int>> GetEnumerator()
{
return _valueCounter.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
Upvotes: 1
Reputation: 11938
This does what you want, but will reorder the elements in your original collection.
var query = yourArray.GroupBy(x=>x)
.Where(x=>x.Count() > 1)
.SelectMany(x=>x)
.ToArray();
To get the difference between the two, you can then use Except, doing:
var exceptResult = yourArray.Except(query);
Upvotes: 2