This is a very easy problem that I have been stuck on.
I have a IEnumerable IGrouping object with grouped up common key items in it. I now need to compare each of the same common key item in the IEnumerable IGrouping object itself. I used 2 foreach loop to achieve that but the problem is the foreach causes repetition. I need to loop and compare each item without repetition of the one which already went through.
Parallel.ForEach((sameQuickHashGroups, quickHashGroup) =>
{
foreach (var groupFile in quickHashGroup)
{
foreach (var groupFile2 in quickHashGroup)
{
if (HashTool.ByteToByteCompare(groupFile.FileName, groupFile2.FileName))
{
groupFile.FullHash = count.ToString();
groupFile2.FullHash = count.ToString();
}
}
count;
}
});
Can anyone solve this?
Assuming I understand the question now (as apposed to my first answer), You are basically asking how to compare each pair of elements only once.
I would use Linq's ToList()
on the IEnumerable, and then use for
loops instead of foreach
loops.
This way you can compare each pair of elements only once:
var quickHashGroupList = quickHashGroup.ToList();
for(var i = 0; i < quickHashGroupList.Count-1; i++)
{
var groupFile = quickHashGroupList[i];
for(var j = i+1; j < quickHashGroupList.Count; j++)
{
var groupFile2 = quickHashGroupList[j];
if (HashTool.ByteToByteCompare(groupFile.FileName, groupFile2.FileName))
{
groupFile.FullHash = count.ToString();
groupFile2.FullHash = count.ToString();
}
}
}
Note that the first loop goes only to count-2, since the second loop starts at i+1.