var _array = new int[] { -4, -2, -1, 1, 2, 4 };
var keepPerms = new List<List<int>>();
var _l = new List<int>();
var c = 0;
while (c != 2)
{
for (int i = 0;i < _array.Length; i )
{
_l.Add(_array[i]);
List<int> _sort = _l.OrderBy(s => s).ToList();
if (!keepPerms.Contains(_sort))
keepPerms.Add(_sort);
}
_l.Clear();
c ;
}
foreach (var item in keepPerms)
{
{
Console.WriteLine(String.Join(" ", item));
}
Console.WriteLine();
}
Console.WriteLine();
Output i get:
-4
-4 -2
-4 -2 -1
-4 -2 -1 1
-4 -2 -1 1 2
-4 -2 -1 1 2 4
-4
-4 -2
-4 -2 -1
-4 -2 -1 1
-4 -2 -1 1 2
-4 -2 -1 1 2 4
Output i need:
-4
-4 -2
-4 -2 -1
-4 -2 -1 1
-4 -2 -1 1 2
-4 -2 -1 1 2 4
It's a prototype of method where i need to find subsets of some sequnce. The main problem is that after doing this method i get duplicates of subsets. Is there any way to get the original values of list, despite the number of times I called it? Can you advise better way to find thise originals values of list.
CodePudding user response:
List.Contains() use default equality comparer. List<int> a == List<int> b
only if it's same objects.
You should use custom equality comparer in Contains()
or use Any SequenceEqual
:
if (!keepPerms.Any(item => item.SequenceEqual(_sort)))
keepPerms.Add(_sort);
CodePudding user response:
You get two results because of the condition while(c != 2), you can switch it to while(c != 1) and will work or you can just remove the while as is not really helpful in your case.