技術メモ(主に自分向け)

短期記憶の自分向けの技術メモです。

ランダムでレコードを抽出する方法

ランダムでレコードを抽出する方法は以下の通り。
【やりたいこと/前提条件】
 ・5レコード抽出
 ・重複なし
 ・オブジェクト:testObject
 ・項目に一意の数字(Index__c)を保持
 ・insertTestはWrapperクラス。Stirng型のNameとInsertIndexという変数を持っていて、抽出したレコードを格納する。

List<insertTest> insertTestList = new List<insertTest>();
List<testObject__c> toList = [SELECT 
               Id,
               Name,
               Index__c
             From
               testObject];

for (Integer i = 0, insertTestList .size() < 5; i++) {
 insertTest it = new insertTest();
 Integer rand = Math.round(Math.random() * (toList.size() - 1));
 String strIndex = toList[rand].Index__c;
 Boolean checkFlag = false;

 //ランダムで抽出したレコードが既にリストに入っていないか確認
 for (Integer j = 0; j < insertTestList.size(); j++) {
  if (insertTestList [j].InsertIndex.equales(strIndex)) {
   checkFlag = true;
   break;  
  }
  else {
   checkFlag = false;
  }
 }
 //ランダムで抽出したレコードを抽出用リストに格納
 if (!checkFlag) {
  insertTest.Name = toList[rand].Name;
  insertTest.InsertIndex = toList[rand].index__c;
 }
}

・Wrapperクラス

public class insertTest {
 @AuraEnabled public String Name {get; set;};
 @AuraEnabled public String InsertIndex {get; set;};

 public insertTest() {
  Name = '';
  InsertIndex = '';
 } 
}