Reputation: 385
I have an extracted list which contains only numbers whose addition is greater than 80 and also filtered to 10 random numbers.
How to ensure that the same value does not occur more than twice in the list of 4 numbers?
So { 20, 20, 20, 5 }
would not be ok but { 20, 5, 20, 3 }
would be fine.
I've tried using Distinct
but it seems it ensure that the entire list is unique, not what I need.
var numList = new List<int> { 5, 20, 1, 7, 19, 3, 15, 60, 3, 21, 57, 9 };
var extractedList = (from n1 in numList
from n2 in numList
from n3 in numList
from n4 in numList
where n1 + n2 + n3 + n4 > 80
select new { n1, n2, n3, n4, Rnd = rnd.NextDouble() })
.OrderBy(z => z.Rnd)
.Take(10)
.ToList();
Upvotes: 2
Views: 272
Reputation: 101142
You could create an array of the selected values, group them, and check that each group has no more than two members.
For example:
var extractedList = (from n1 in numList
from n2 in numList
from n3 in numList
from n4 in numList
where n1 + n2 + n3 + n4 > 80 &&
new int[]{n1, n2, n3, n4}
.GroupBy(x => x)
.Max(g => g.Count()) <= 2
select new { n1, n2, n3, n4, Rnd = rnd.NextDouble() })
.OrderBy(z => z.Rnd)
.Take(10)
.ToList();
Upvotes: 4