2017年5月15日 星期一

Unity內用C#尋找比對在Dictionary內Structure的屬性資料

Dictionary可以塞各種不同格式的資料,我比較常用的是放Structure,這樣可以把一個個體的各種屬性資料都放在一塊;但當要條件式比對或尋找裡面的某一個屬性資料時,就有點麻煩,因此在這裡做一個記錄。
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using System.Linq;
  5.  
  6. public class XXX : MonoBehaviour {
  7.  
  8.     public struct playerDataStruct
  9.     {
  10.         public string nickName;
  11.         public int age;
  12.         public int score;
  13.     }
  14.  
  15.     private Dictionary<string, playerDataStruct> playerDataDictionary = new Dictionary<string, playerDataStruct>();
  16.     private playerDataStruct tempPlayerDataStruct = new playerDataStruct();
  17.  
  18.     void Start ()
  19.     {
  20.         tempPlayerDataStruct.nickName = "Warrior";
  21.         tempPlayerDataStruct.age = 18;
  22.         tempPlayerDataStruct.score = 1000;
  23.  
  24.         playerDataDictionary.Add("John", tempPlayerDataStruct);
  25.  
  26.         tempPlayerDataStruct.nickName = "Fighter";
  27.         tempPlayerDataStruct.age = 20;
  28.         tempPlayerDataStruct.score = 2000;
  29.  
  30.         playerDataDictionary.Add("Peter", tempPlayerDataStruct);
  31.  
  32.         //----------------------------------------------------------------------------------------------------------------
  33.  
  34.         if (playerDataDictionary.Values.Any(x => x.age >= 20) == true)
  35.         {
  36.             Debug.Log("本遊戲有大於20歲以上的玩家。");
  37.         }
  38.  
  39.         Debug.Log("本遊戲內小於20歲的玩家第一人為:" + playerDataDictionary.Where(x => x.Value.age < 20).Select(x => x.Key).FirstOrDefault());
  40.     }
  41.  
  42.     void Update ()
  43.     {
  44.  
  45.     }
  46. }
一般比較常見的情況有:
1.使用Value去逆向尋找Key。
2.判斷此Dictionary內是否包含該Key或是該Value。
3.直接尋找或比對Structure內的某一個屬性。

自己所知的對應方式:

依據條件把找到Key的全都取出
playerDataDictionary.Where(x => x.Value.age < 20).Select(x => x.Key)

取出找到的第一個Key
playerDataDictionary.Where(x => x.Value.age > 20).Select(x => x.Key).FirstOrDefault())
playerDataDictionary.FirstOrDefault(x => x.age >= 20).Key

判斷有無該Key包含在內
playerDataDictionary.ContainsKey("Peter")

判斷有無該Value的屬性包含在內
playerDataDictionary.Values.Any(x => x.age >= 20)

沒有留言:

張貼留言