Whats the most concise way to pick a random element by weight in c#?

后端 未结 4 1996
慢半拍i
慢半拍i 2021-01-02 03:57

Lets assume:

List which element is:

public class Element(){
   int Weight {get;set;}
}

What I want to a

4条回答
  •  [愿得一人]
    2021-01-02 04:32

    // assuming rnd is an already instantiated instance of the Random class
    var max = list.Sum(y => y.Weight);
    var rand = rnd.Next(max);
    var res = list
        .FirstOrDefault(x => rand >= (max -= x.Weight));
    

提交回复
热议问题