Reputation: 41
I want to compare two objects with all possible variations. How can I do that.
var _entries = new List<string>();
_entries.Add("Awesom");
_entries.Add("Awesom");
_entries.Add("Awesom");
_entries.Add("Awesom");
int count = 0;
for (int i = 1; i < _entries.Count; i++)
{
if (_entries[i].Equals(_entries[i - 1]))
{
count++;
}
}
Console.Write(count);
Console.ReadLine();
This one compares in sequential order but it should compare with every possible scenario.
The expected result should be 4
because there are 4
same objects in array.
Upvotes: 2
Views: 217
Reputation: 849
When you say This one compares in sequential order but it should compare with every possible scenario. I believe you are expecting value of count = 16. As by comparing with every possible values you'll have 16 combinations and as all the values are equal you'll get count as 16.
var _entries = new List<string>();
_entries.Add("Awesom");
_entries.Add("Awesom");
_entries.Add("Awesom");
_entries.Add("Awesom");
var query = from e1 in _entries
from e2 in _entries
where e1 == e2
select $"{e1} x {e2}";
var count = query.Count();
Try printing values of query variable and you'll see all combinations.
Upvotes: 0
Reputation: 186668
I suggest using Linq, GroupBy:
using System.Linq;
...
// No Sequential Order test
var _entries = new List<string>() {
"Awesom",
"Bar",
"Awesom",
"Awesom",
"Foo",
"Awesom",
"Bar",
};
int count = _entries
.GroupBy(item => item)
.Sum(group => group.Count() - 1);
with a help of GroupBy
we obtain 3
groups:
4 items of "Awesom"
1 items of "Foo"
2 items of "Bar"
then we can just Count
items in each group and Sum
them: (4 - 1) + (1 - 1) + (2 - 1) == 4
duplicates overall.
Upvotes: 5