Lets assume:
List<element>
which element is:
public class Element {
int Weight { get; set; }
}
What I want to achieve is, select an element randomly by the weight. For example:
Element_1.Weight = 100;
Element_2.Weight = 50;
Element_3.Weight = 200;
So
- the chance
Element_1
got selected is 100/(100+50+200)=28.57% - the chance
Element_2
got selected is 50/(100+50+200)=14.29% - the chance
Element_3
got selected is 200/(100+50+200)=57.14%
I know I can create a loop, calculate total, etc...
What I want to learn is, whats the best way to do this by Linq in ONE line (or as short as possible), thanks.
UPDATE
I found my answer below. First thing I learn is: Linq is NOT magic, it's slower then well-designed loop.
So my question becomes find a random element by weight, (without as short as possible stuff :)
If you want a generic version (useful for using with a (singleton) randomize helper, consider whether you need a constant seed or not)
usage:
code: