c# - How to select random elements from list exclude some list? -


so have cardbase abstract class , want extract random card elements exclude specific card list. did this.

public list<cardbase> getrandexclude(list<cardbase> list, int elementscount, list<cardbase> excludelist) {             var returncards = card in list                                !excludelist.contains(card)                                select card;     foreach (cardbase cd in returncards.take(elementscount))     {         debug.log("selected random card "+cd.name);     }     return (list<cardbase>) returncards.take(elementscount); } 

did right? there better way? in advance.


so changed little this. , seems works.

public list<cardbase> getrandexclude(list<cardbase> list, int elementscount, list<cardbase> excludelist) {             var returncards = card in list                                !excludelist.contains(card)                                select card;     foreach (cardbase cd in returncards.orderby(arg => guid.newguid()).take(elementscount).tolist())     {         debug.log("selected random card "+cd.name);     }     return returncards.orderby(arg => guid.newguid()).take(elementscount).tolist(); } 

you go linq route , use except provided cardbase has form of equality comparison. other wise use overload , provide iequalitycomparer<cardbase> comparer

from there want randomly select cards available cards remaining.

static random randomizer = new random(); public list<cardbase> getrandexclude(list<cardbase> list, int elementscount, list<cardbase> excludelist) {     var availablecards = list.except(excludelist).tolist();     int count = math.min(elementscount, availablecards.count);     var selectedcards = new hashset<cardbase>();     do{         var index = randomizer.next(0, availablecards.count);         var card = availablecards[index];         selectedcards.add(card);     } while (selectedcards.count < count);     foreach (cardbase cd in selectedcards) {         debug.log("selected random card " + cd.name);     }     return selectedcards.tolist(); } 

Comments

Popular posts from this blog

node.js - Node js - Trying to send POST request, but it is not loading javascript content -

javascript - Replicate keyboard event with html button -

javascript - Web audio api 5.1 surround example not working in firefox -