以下似乎有效:
void Main()
{
var items = new []{"kiwi", "orange", "cherry", "apple"};
var weights = new[]{0.1f, 0.1f, 0.2f, 0.6f};
var faveFaker = new Faker<Favorite>()
.RuleFor(x => x.Fruit, f => f.Random.WeightedRandom(items, weights));
faveFaker.Generate(10).Dump();
}
public class Favorite
{
public string Fruit {get;set;}
}
![在此处输入图像描述](https://i.stack.imgur.com/tIcUG.png)
当然,使用 C# 扩展方法始终是扩展 Bogus 以最适合您的 API 需求的绝佳方式:
void Main()
{
var faveFaker = new Faker<Favorite>()
.RuleFor(x => x.Fruit, f => f.WeightedRandom( ("kiwi", 0.1f), ("orange", 0.1f),
("cherry", 0.2f), ("apple", 0.6f)) );
faveFaker.Generate(10).Dump();
}
public class Favorite
{
public string Fruit {get;set;}
}
public static class MyExtensionsForBogus
{
public static T WeightedRandom<T>(this Faker f, params (T item, float weight)[] items)
{
var weights = items.Select(i => i.weight).ToArray();
var choices = items.Select(i => i.item).ToArray();
return f.Random.WeightedRandom(choices, weights);
}
}
![在此处输入图像描述](https://i.stack.imgur.com/gUPy9.png)