103 lines
2.2 KiB
C#
103 lines
2.2 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using UnityEngine;
|
|
|
|
namespace BitStrap.Examples
|
|
{
|
|
public class DictionaryExtensionsExample : MonoBehaviour
|
|
{
|
|
[Serializable]
|
|
public struct Pair
|
|
{
|
|
public string key;
|
|
|
|
public int value;
|
|
}
|
|
|
|
[Header("Edit the fields and click the buttons to test them!")]
|
|
public Pair[] dictionary = new Pair[4]
|
|
{
|
|
new Pair
|
|
{
|
|
key = "element0",
|
|
value = 0
|
|
},
|
|
new Pair
|
|
{
|
|
key = "element1",
|
|
value = 1
|
|
},
|
|
new Pair
|
|
{
|
|
key = "element2",
|
|
value = 2
|
|
},
|
|
new Pair
|
|
{
|
|
key = "element3",
|
|
value = 3
|
|
}
|
|
};
|
|
|
|
private Dictionary<string, int> actualDictionary = new Dictionary<string, int>();
|
|
|
|
[Button]
|
|
public void ForEachIterationWithNoGarbage()
|
|
{
|
|
BuildDictionary();
|
|
DictionaryExtensions.GCFreeEnumerator<string, int> enumerator = actualDictionary.Each().GetEnumerator();
|
|
while (enumerator.MoveNext())
|
|
{
|
|
KeyValuePair<string, int> current = enumerator.Current;
|
|
Debug.LogFormat("This is an iteration. Key = {0}, Value = {1}", current.Key, current.Value);
|
|
}
|
|
}
|
|
|
|
[Button]
|
|
public void ElementZeroCount()
|
|
{
|
|
BuildDictionary();
|
|
Debug.LogFormat("There are {0} zeros values in the dictionary.", actualDictionary.Count((KeyValuePair<string, int> e) => e.Value == 0));
|
|
}
|
|
|
|
[Button]
|
|
public void AreAllZeros()
|
|
{
|
|
BuildDictionary();
|
|
Debug.LogFormat("Are all values in dictionary zero? {0}.", actualDictionary.All((KeyValuePair<string, int> e) => e.Value == 0));
|
|
}
|
|
|
|
[Button]
|
|
public void IsThereAnyZeros()
|
|
{
|
|
BuildDictionary();
|
|
Debug.LogFormat("Is there any zero element value in dictionary? {0}.", actualDictionary.Any((KeyValuePair<string, int> e) => e.Value == 0));
|
|
}
|
|
|
|
[Button]
|
|
public void GetFirstElementOrDefaultValue()
|
|
{
|
|
BuildDictionary();
|
|
Debug.LogFormat("First element value or default value is {0}.", actualDictionary.FirstOrDefault().Value);
|
|
}
|
|
|
|
[Button]
|
|
public void PrettyPrintDictionary()
|
|
{
|
|
BuildDictionary();
|
|
Debug.Log(actualDictionary.ToStringFull());
|
|
}
|
|
|
|
private void BuildDictionary()
|
|
{
|
|
actualDictionary.Clear();
|
|
Pair[] array = dictionary;
|
|
for (int i = 0; i < array.Length; i++)
|
|
{
|
|
Pair pair = array[i];
|
|
actualDictionary.Add(pair.key, pair.value);
|
|
}
|
|
}
|
|
}
|
|
}
|