I have a List<Fruit>
,
public class Fruit
{
public string Name { get; set; }
public string Type { get; set; }
}
and the list above contains 30 Fruit objects of two types: Apple
and Orange
. 20 apples and 10 oranges.
List<Fruit> fruits = new List<Fruit>();
fruits.Add(new Fruit(){ Name = "Red Delicious", Type = "Apple" });
fruits.Add(new Fruit(){ Name = "Granny Smith", Type = "Apple" });
fruits.Add(new Fruit(){ Name = "Sour Granny", Type = "Orange" });
fruits.Add(new Fruit(){ Name = "Delicious Yummy", Type = "Orange" });
.....
How can I get a list of 10 random fruits (from the basket of 30 fruits), but there should be 3 oranges and 7 apples?
Random number in a fixed length. Supposing you want to generate a random number string in 6-digit length, you can use this formula. =RANDBETWEEN (100000,999999) Press Enter key, then then a random number in 6-digit length is outputted. Note: The output number will be changed when every time the worksheet is updated.
Random number in a fixed length Supposing you want to generate a random number string in 6-digit length, you can use this formula =RANDBETWEEN (100000,999999) Press Enter key, then then a random number in 6-digit length is outputted.
Random number in a changed length based on the digit number you type in another cell In some times, you may need to generate passwords in different lengths, for instance, when you type 5 in cell A1, the cell A2 will display a random number in 5-dighit length, if you type 9 in cell A1, the A2 displays a 9-digit number.
The issue of generation of random numbers is quite common, but sometimes, we have applications that require us to better that and provide some functionality of generating a random string of digits and alphabets for applications such as passwords. Let’s discuss certain ways in which this can be performed.
You can use LINQ and Guid
or Random
to make a random selection:
var apples = fruits.
Where( f => f.Type == "Apple" ). //choose only from apples
OrderBy( f => Guid.NewGuid() ). //order randomly
Take( 7 ). //take 7 apples
ToList();
The same goes for oranges
, just with "Orange"
instead of "Apple"
and with 3 instead of 7.
OrderBy
sorts the enumerable by the given condition. Because Guid.NewGuid()
returns a random unique identifier, the result is that the items are ordered randomly. When we then apply Take( n )
, it will take the n
first items in this random order.
Note that instead of Guid
you can create an instance of Random
and the use f => random.NextDouble()
as the OrderBy
expression. This is potentially a safer solution, because Guid.NewGuid()
is not guaranteed to be random, only to be unique.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With