if both values are equal to each other then do this c# - c#

First of all, here's my script:
using UnityEngine;
using System.Collections;
using Steamworks;
public class Achievements : MonoBehaviour {
public static int currentScore=0;
public static int score300 = 300;
public static int score1000 = 1000;
public static int score3600 = 3600;
public static int score18000 = 18000;
public static int score72000 = 72000;
public static int score180000 = 180000;
void Start() {
if(SteamManager.Initialized) {
string name = SteamFriends.GetPersonaName();
Steamworks.SteamUserStats.SetAchievement("NEW_ACHIEVEMENT_1_0");
Steamworks.SteamUserStats.StoreStats();
Debug.Log(name);
}
}
void Update()
{
currentScore = PlayerPrefs.GetInt("highscore");
if (currentScore == score300 && SteamManager.Initialized){
Steamworks.SteamUserStats.SetAchievement("NEW_ACHIEVEMENT_5_0");
Steamworks.SteamUserStats.StoreStats();
}
if (currentScore == score1000 && SteamManager.Initialized) {
Steamworks.SteamUserStats.SetAchievement("NEW_ACHIEVEMENT_6_0");
Steamworks.SteamUserStats.StoreStats();
}
if (currentScore == score3600 && SteamManager.Initialized) {
Steamworks.SteamUserStats.SetAchievement("NEW_ACHIEVEMENT_7_0");
Steamworks.SteamUserStats.StoreStats();
}
if (currentScore == score18000 && SteamManager.Initialized) {
Steamworks.SteamUserStats.SetAchievement("NEW_ACHIEVEMENT_8_0");
Steamworks.SteamUserStats.StoreStats();
}
}
}
As you can see, I have public integers that hold variety of numbers. I am also using current steamworks.net, and I'm trying to see if I can match both "highscore" (which is already set up and working properly) with scoreXXX. If that happens, I want script to drop an achievement.
Am I executing if(x=x) function wrong? Can someone please help?

The problem is you arent checking if the score is greater than the score benchmarks, only that its equal.
You could simplify your code a bit by putting these values into a Dictionary<int, string>:
private static Dictionary<int, string> highScoreDictionary = new Dictionary<int, string>()
{
{ 300, "NEW_ACHIEVEMENT_5_0" },
{ 1000, "NEW_ACHIEVEMENT_6_0" },
{ 3600, "NEW_ACHIEVEMENT_7_0" },
{ 18000, "NEW_ACHIEVEMENT_8_0" },
{ 72000, "NEW_ACHIEVEMENT_9_0" },
{ 180000, "NEW_ACHIEVEMENT_10_0" }
};
void Update()
{
currentScore = PlayerPrefs.GetInt("highscore");
if(SteamManager.Initialized)
{
//Order by high score, descending
foreach(var score in highScoreDictionary.OrderByDescending(x => x.Key))
{
//If the score is greater than or equal to the benchmark
//Then add the achievement
if(currentScore >= score.Key)
{
Steamworks.SteamUserStats.SetAchievement(score.Value);
Steamworks.SteamUserStats.StoreStats();
break;
}
}
}
}
I made a fiddle here. Its obviously modified a bit since I dont have access to Unity libraries there, but you can see the logic in action.

Related

Why does the method List.Add isn't working?

I have a game developed with unity, this is the code of a button. It should take the public List of the script "BoardScript" and add a number to this list, but, for some reason it isn't working.
I have checked that the Button click is working (as you can see, in the code the debug.log yes prints), but clicking it is not adding the number to my list.
In the "BoardScript" I added some numbers just to try, and the value adds to the list successfully, so, I guess that the error is somewhere in this script, but I can't figure what can be wrong.
Can you please help me?
private Button B;
void Start()
{
B = GetComponent<Button>();
B.onClick.AddListener(Clicker);
}
void Clicker()
{
BoardScript boardScript = new BoardScript();
int Two = 2;
boardScript.UserList.Add(Two);
Debug.Log("Added);
}
// Update is called once
EDIT
I almost forgot to tell a detail. I have write Debug.Log(UserList.Count) and The value is 1, even if I added 1 several times as the button script suggests (Its the same script but with different object).
So, As Steve Said This is the BoardScript code, it is a little long.
private int[] PreList = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
private List<int> ButtonList = new List<int>();
public List<int> UserList = new List<int>();
private System.Random Rnd = new System.Random();
public List<int> EndList = new List<int>();
void Randomizer()
{
PreList = PreList.OrderBy(C => Rnd.Next()).ToArray();
foreach (var item in PreList)
{
Debug.Log(item.ToString());
if (item == 1)
{
OneMethod();
}
if (item == 2)
{
TwoMethod();
}
if (item == 3)
{
ThreeMethod();
}
if (item == 4)
{
FourMethod();
}
if (item == 5)
{
FiveMethod();
}
if (item == 6)
{
SixMethod();
}
if (item == 7)
{
SevenMethod();
}
if (item == 8)
{
EightMethod();
}
if (item == 9)
{
NineMethod();
}
}
EndList = PreList.ToList();
}
void OneMethod()
{
//yield return new WaitForSeconds(1);
ButtonList.Add(1);
}
void TwoMethod()
{
ButtonList.Add(2);
}
void ThreeMethod()
{
ButtonList.Add(3);
}
void FourMethod()
{
ButtonList.Add(4);
}
void FiveMethod()
{
ButtonList.Add(5);
}
void SixMethod()
{
ButtonList.Add(6);
}
void SevenMethod()
{
ButtonList.Add(7);
}
void EightMethod()
{
ButtonList.Add(8);
}
void NineMethod()
{
ButtonList.Add(9);
}
void Start ()
{
Randomizer();
string[] the_array = ButtonList.Select(i => i.ToString()).ToArray();
string OrderString = string.Join(", ", the_array);
GameObject.Find("Order").GetComponent<Text>().text = OrderString;
UserList.Add(1);
UserList.Add(5);
}
IEnumerator Waiter()
{
yield return new WaitForSeconds(10);
}
// Update is called once per frame
void Update()
{
string[] the_array = UserList.Select(i => i.ToString()).ToArray();
string OrderString = string.Join(", ", the_array);
Debug.Log(OrderString);
if (UserList.Count == 8)
{
if (UserList == ButtonList)
{
//Sound
BehaviourModel B = new BehaviourModel();
B.Counter++;
if (B.Counter < 10)
{
SceneManager.LoadScene(B.SceneArray[B.Counter]);
}
else if (B.Counter > 10)
{
SceneManager.LoadScene("MainMenuScene");
}
}
else if (UserList != ButtonList)
{
UserList.Clear();
Debug.Log("Fail");
}
}
}
Each time you click the button you create a new instance of BoardScript. You should store the boardScript variable as a variable in your class or separate component to ensure the data will persist.
You can do either create only one Instance, like:
private Button B;
BoardScript boardScript = new BoardScript();
then in your void Clicker() method:
add item to UserList.
Or:
You can create a static variable in your BoardScript class and check for null. If its null, then create a new instance else return an old instance.
The following code will help:
private static BoardScript _uniqueBoardScript;
private BoardScript()
{}
public static BoardScript GetInstance()
{
if(_uniqueBoardScript==null)
{
_uniqueBoardScript = new BoardScript();
}
return _uniqueBoardScript;
}
and from your void Clicker()
{
BoardScript boardScript = BoardScript.GetInstance();
int Two = 2;
boardScript.UserList.Add(Two);
Debug.Log("Added);
}

Processing int to name of list

I try to write a simple console application with Hanoi towers. But I am stuck at one point.
In my program I ask a person to write from to which tower wants to put the disk, but: I have 3 lists as towers, I'll ask for a number from gamer and now how I can build a "compare method"? Because I don't want to copy the same piece of code 6 times...
class Towers : Disks
{
//public Towers(int Value, int WhereItIs) : base(Value, WhereItIs) { }
public List<Disks> Tower1 = new List<Disks>();
public List<Disks> Tower2 = new List<Disks>();
public List<Disks> Tower3 = new List<Disks>();
public void Compare(int dyskFrom, int dyskWhere) {
}
public void Display() {
foreach(var i in Tower1){
Console.WriteLine("Where: {0} | Value: {1}", i.WhereItIs, i.Value);
}
}
public void Build(int TowerHigh) {
for (int i = TowerHigh; i > 0; i--) {
Tower1.Add(new Disks {Value = i, WhereItIs = 1 });
}
}
}
class Disks
{
public int Value; //wartosc krazka
public int WhereItIs; //na ktorej wiezy sie on znajduje
}
class Program
{
static void Main(string[] args)
{
Towers Tower = new Towers();
int TowerHigh;
Console.Write("Podaj wysokość wieży: ");
TowerHigh = int.Parse(Console.ReadLine());
Tower.Build(TowerHigh);
Tower.Display();
Tower.Compare(1, 2);
}
}
It's easier to create an array of Stack<Disk>(). This way you can select a tower by index.
I would use a Stack, because thats typically the functionality you need.
Something like: PSEUDO (typed in browser, no syntax checked)
class Disk
{
public int Size {get; set;}
}
static void Main(string[] args)
{
// create the Stack<Disk> array
Stack<Disk>[] towers = new Stack<Disk>[3];
// create each tower
for(int i=0;i<towers.Length;i++)
{
towers[i] = new Stack<Disk>();
// fill the towers.
for(int j=3;j>0;j--)
towers[i].Enqueue(new Disk { Size = j });
}
bool isHoldingDisk = false;
while(true)
{
DisplayTowers(towers);
if(isHoldingDisk)
Console.WriteLine("On what tower do you want to place it?");
else
Console.WriteLine("Choose a tower to pick a disk");
var key = Console.ReadKey(true);
var chosenTowerIndex = 0;
switch(key)
{
case(Key.Escape):
break;
case(Key.D1):
chosenTowerIndex = 0;
break;
case(Key.D1):
chosenTowerIndex = 1;
break;
case(Key.D1):
chosenTowerIndex = 2;
break;
// etc...
}
if((chosenTowerIndex < 1) || (chosenTowerIndex >= towers.Length))
continue;
// check here if you are holding a disk
if(isHoldingDisk)
{
// logic for testing if you can place the disk here...
// using towers[chosenTowerIndex]
// check if it is completed...
if(completed)
break;
isHoldingDisk = false;
}
else
{
// check if you can pickup a disk....(if there is any)
isHoldingDisk = true;
}
}
// final display...
DisplayTowers(towers);
Console.WriteLine("Thanks for playing");
}
static void DisplayTowers(Stack<Disk>[] towers)
{
// draw some fancy asc-ii art...
}

Unity, C#, Dictionary, calculating scores of teams in a match

ok its hard for me to wrap my head around this as it is so ill try to explane as clearly as I can what my problem is.
First of all im creating a score system for a fps game that im making.
now right now the score system uses a dubble Dictionary structure that is it has a Dictionary inside a Dictionary.
playerScores = new Dictionary<string, Dictionary<string, int> > ();
the first dictionary is creating a list of user names the 2nd dictionery is used to hold 4 keys (kills, deaths, assists, teamID)
so basicley its
playerScores[username][scoretype][scorevalue]
now it currently storing the kills and deaths of players and then is displaying them in a leader board in descending order of kills and are grouped in what team they are in and that's working all fine.
the issue I am having is trying to work out a way to calculate the teams current score for each team. and also work out what team has the highest score. I just cant get my head around it.
this here is the class that handles this data (not the leaderboard code but the scoring and stuff).
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
public class MyMatchData : MonoBehaviour
{
Dictionary<string, Dictionary<string, int> > playerScores;
int changeCounter = 0;
public GameObject scoreBoard;
Canvas scoreBoardCan;
public float myTeamID = 0f;
string playerNameKey = "blank";
float myDeaths = 0f;
float myKills = 0f;
// Use this for initialization
void Start ()
{
scoreBoardCan = scoreBoard.transform.parent.GetComponent<Canvas> ();
myDeaths = 0f;
myKills = 0f;
}
void Init ()
//init is just to make shure that we know playerscores is set b4 some one trys to use it
//(when ever some one calls the playerscores first they will call Init())
{
if (playerScores != null) {
return;
}//If the player scores has been set then return out so we dont erase the scores
playerScores = new Dictionary<string, Dictionary<string, int> > (); //must tell it that theres a new dictionery else u will get null error
//playerScores [playerNameKey] = new Dictionary<string, int> (); // agane must tell it theres a new dictionery because this is the sub dictionery
//a new sub dictionerey must be created for evey player. setScore() will create a new sjub dictionerey for a player if one dose not yet exsist.
}
void Update ()
{
if (Input.GetKeyDown (KeyCode.Tab)) {
changeCounter ++;
//scoreBoard.SetActive ( !scoreBoard.activeSelf);
bool scoreBoardCanIsActive = scoreBoardCan.enabled;
scoreBoardCan.enabled = !scoreBoardCanIsActive;
}
if (Input.GetKeyDown (KeyCode.P)) {
ChangeScore ("sky", "kills", 1);
}
}
[RPC]
public void playerDied (bool wasBot, bool wasKilledBySomeone, string killedBy, string playerName, int playerTeam)
{
if (PhotonNetwork.isMasterClient) {
if (wasBot) {
Health hlscBot = GameObject.Find (playerName).GetComponent<Health> ();
hlscBot.GetComponent<PhotonView> ().RPC ("DeSpawn", PhotonTargets.AllBuffered, "bot", playerName, playerName, playerTeam);
} else {
//player respawn stuff here
Debug.Log ("Host MyMatchData " + playerName);
Health hlsc = GameObject.Find (playerName).GetComponent<Health> ();
hlsc.GetComponent<PhotonView> ().RPC ("DeSpawn", PhotonTargets.AllBuffered, "player", playerName, "null", -1);
}
//do Score dumping stuff here
if (wasKilledBySomeone == true) {
ChangeScore (playerName, "deaths", 1);//increase the players deaths
ChangeScore (killedBy, "kills", 1);//increase the killers score
} else {
ChangeScore (playerName, "deaths", 1);//increase the players deaths
}
}
}
[RPC]
public void firstSpawn (string userName, int teamID)
{
if (!PhotonNetwork.isMasterClient) {
return;
}
SetScore (userName, "kills", 0);
SetScore (userName, "deaths", 0);
SetScore (userName, "assists", 0);
SetScore (userName, "teamID", teamID);
}
public int GetScore (string username, string scoreType)
{
Init ();
if (playerScores.ContainsKey (username) == false) { //this just meens if the player name receaved has not reconised then it must not of been set yet
return 0;// return the player score as 0
}
if (playerScores [username].ContainsKey (scoreType) == false) {// at this stage we know the player name is recorded in the dictionery but we need to check if there score has been recorded yet. if not then return 0
return 0;// return the player score as 0
}
return playerScores [username] [scoreType];
}
public void SetScore (string username, string scoreType, int value)
{
Init ();
changeCounter ++;
if (playerScores.ContainsKey (username) == false) {//if the player has not been recorded in the dictionery yet.
playerScores [username] = new Dictionary<string, int> ();// Creates a new dictinerey(sub dictionery) for that player.
}
playerScores [username] [scoreType] = value; // the players score is now the value of value
}
public void ChangeScore (string username, string scoreType, int amount)
{
Init ();
int currScore = GetScore (username, scoreType);
SetScore (username, scoreType, currScore + amount);
}
public string[] GetPlayerNames ()
{
Init ();
return playerScores.Keys.ToArray ();
}
public string[] GetPlayerNames (string sortingScoreType)
{
Init ();
string[] names = playerScores.Keys.ToArray (); //have to convert to array because keys dont retun a array but a list of string of keys or somthing
return names.OrderByDescending (n => GetScore (n, sortingScoreType)).ToArray (); //this needs to beconverted toArray because of the same issue above
// ok so the names in this array (names) gets sorted by running the getscore function to find out who has what score. its complacated but works
//for that to work you need using System.Linq
}
public int GetChangeCounter ()
{
return changeCounter;
}
}
can any one help me work out some code to calculate the teams scores?
also there may be 2 teams or 3 or even 12 teams it just depends on how the match is set up.
also most of the comments in the code are for my understanding of the code when I wrote it.
First:
float myDeaths = 0f;
float myKills = 0f;
Unless you can achieve half death / quarter death or even 0.1569865 death, use int.
What I would have done something like this:
internal class Game
{
public List<Team> Teams { get; set; }
public void firstSpawn(string userName, int teamID)
{
if (!PhotonNetwork.isMasterClient)
{
return;
}
Team team;
if (Teams.Any(t => t.TeamID == teamID))
{
team = Teams.FirstOrDefault(t => t.TeamID == teamID);
}
else
{
team = new Team(teamID);
Teams.Add(team);
}
team.Users.Add(new User(userName));
}
public void playerDied(bool wasBot, bool wasKilledBySomeone, User killer, User dead, Team playerTeam)
{
if (PhotonNetwork.isMasterClient)
{
if (wasBot)
{
Health hlscBot = GameObject.Find(dead.Name).GetComponent<Health>();
hlscBot.GetComponent<PhotonView>().RPC("DeSpawn", PhotonTargets.AllBuffered, "bot", dead.Name, dead.Name, playerTeam);
}
else
{
//player respawn stuff here
Debug.Log("Host MyMatchData " + dead.Name);
Health hlsc = GameObject.Find(playerName).GetComponent<Health>();
hlsc.GetComponent<PhotonView>().RPC("DeSpawn", PhotonTargets.AllBuffered, "player", dead.Name, "null", -1);
}
//do Score dumping stuff here
dead.Death(); // The dead is dead, no matter if suicide or not
if (wasKilledBySomeone)
{
killer.Kill();//increase the killers score
}
}
}
public bool getTheHigherTeamBy(Types type)
{
return Teams.Any(team => team.getTeamScore(type) == Teams.Max(t => t.getTeamScore(type)));
}
}
internal class Team
{
public int TeamID { get; set; }
public List<User> Users { get; set; }
public Team(int id = 0)
{
TeamID = id;
}
public int getTeamScore(Types type)
{
return Users.Sum(u => u.Score.getScoreFromType(type));
}
public string[] getPlayerNames()
{
return Users.Select(u => u.Name).ToArray();
}
public string[] GetPlayerNames(Types sortingScoreType)
{
return Users.OrderByDescending(u => u.Score.getScoreFromType(sortingScoreType)).Select(u => u.Name).ToArray();
}
}
public enum Types
{
Kill,
Death,
Assist // Not sure about that one
}
internal class Score
{
private readonly Dictionary<Types, int> points = new Dictionary<Types, int>();
public Score()
{
// Fill the dictionnary with all the available types
foreach (Types type in Enum.GetValues(typeof(Types)))
{
points.Add(type, 0);
}
}
public int getScoreFromType(Types type)
{
return points[type];
}
public void incrementScoreForType(Types type, int amount = 1)
{
points[type] += amount;
}
}
internal class User
{
public string Name { get; set; }
public Score Score { get; set; }
public User(string name = "Default")
{
Name = name;
Score = new Score();
}
public int getScoreFromType(Types type)
{
return Score.getScoreFromType(type);
}
public void changeScore(Types type, int amount)
{
Score.incrementScoreForType(type, amount);
}
public void Death()
{
Score.incrementScoreForType(Types.Death);
}
public void Kill()
{
Score.incrementScoreForType(Types.Kill);
}
public void Assist()
{
Score.incrementScoreForType(Types.Assist);
}
}
In general, it's better to work with classes than with strings that represents fake objects: How can you take care of two players named ARandomName which are in the same team?

How to use except and any with strings instead of classes

Like said above how would I, I have some code using linq and except and any(). Currently I use items(a class), to be identified and such, but this is causing problems, so I would like them to be identified by strings instead, but im not sure how. The two functions with the code are: ContainsAllItems, and the other one is in the craft function.
Thanks!
EDIT; To make more clear just in case, right now it checks the items in two lists, instead of that what im asking is how to make it that it checks the itemname of the items in the lists instead, but still make it have the same effect, so it would destroy items and check items and make sure when destroying that not more than needed are destroyed.
If you would not want to look through the code here are the two lines:
public static bool ContainsAllItems(List<Item> a, List<Item> b)
{
return !b.Except(a).Any();
}
and
List<Item> list = new List<Item>();
list = InventoryItems.Except(Recipe.InputItem).ToList();
InventoryItems = list;
Code:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
public class PlayerInventory : MonoBehaviour {
public int MaxInventory = 26;
public List<Item> InventoryItems = new List<Item>();
void OnGUI(){
if (GUILayout.Button ("+5 Wood")) {
AddItem(ItemConstructors.Wood());
AddItem(ItemConstructors.Wood());
AddItem(ItemConstructors.Wood());
AddItem(ItemConstructors.Wood());
AddItem(ItemConstructors.Wood());
}
if (GUILayout.Button ("Craft Wall")) {
Craft(CraftingRecipes.WoodenWall());
}
}
public void AddItem(Item _item){
if (InventoryItems.Count < MaxInventory) {
InventoryItems.Add(_item);
//SaveItems();
}
}
public void RemoveItem(Item _item){
InventoryItems.Remove (_item);
}
public void UseItem(Item _item){
if (_item.ItemType == "Food") {
ConsumeItem(_item);
}
SaveItems();
}
public void ConsumeItem(Item _item){
if (_item.ItemDur > 1) {
_item.ItemDur--;
}
else if(_item.ItemDur <= 1){
RemoveItem(_item);
}
}
public void SaveItems(){
for (int i = 0; i<MaxInventory; i++) {
PlayerPrefs.SetString("Itemn"+i,InventoryItems[i].ItemName);
PlayerPrefs.SetString("Itemt"+i,InventoryItems[i].ItemType);
PlayerPrefs.SetInt("Itemv"+i,InventoryItems[i].ItemValue);
PlayerPrefs.SetInt("Itemd"+i,InventoryItems[i].ItemDur);
}
//LoadItems ();
}
public void LoadItems(){
InventoryItems.Clear();
for (int i = 0; i<MaxInventory; i++) {
Item it = new Item();
it.ItemName = PlayerPrefs.GetString("Itemn"+i);
it.ItemType = PlayerPrefs.GetString("Itemt"+i);
it.ItemValue = PlayerPrefs.GetInt("Itemv"+i);
it.ItemDur = PlayerPrefs.GetInt("Itemd"+i);
if(it.ItemName.Length <= 2 && it.ItemType.Length <= 2){
}
else{
InventoryItems.Add(it);
}
}
}
public void Craft(CraftingItem Recipe){
bool canCraft = ContainsAllItems (InventoryItems,Recipe.InputItem);
if(canCraft){
if(InventoryItems.Count < MaxInventory){
List<Item> list = new List<Item>();
list = InventoryItems.Except(Recipe.InputItem).ToList();
InventoryItems = list;
AddItem(Recipe.OutputItem);
}
else{
Debug.Log("Not enough space!");
}
}
else{
Debug.Log("Invalid Items.");
}
}
public static bool ContainsAllItems(List<Item> a, List<Item> b)
{
return !b.Except(a).Any();
}
}

slightly complex matching condition

The code below represents what I am trying to write. The requirement is that the tax profile should match the correct currency. I have written the if conditions in my code below. However there are more than 100 tax profiles that are read via a database. Should I write if conditions for all 100 of them or is there a better way to code?
using System;
namespace MatchCondition
{
class MatchCondition
{
private const int TaxAmerica1 = 100;
private const int TaxAmerica2 = 200;
private const int TaxIndia1 = 300;
private const int TaxIndia2 = 400;
private const int Rupee =100;
private const int Dollar =200;
static void Main(string[] args)
{
try
{
int currencyId = int.Parse(args[0]);
int taxProfileId = int.Parse(args[1]);
if (currencyId == Rupee && (taxProfileId == TaxIndia1 || taxProfileId == TaxIndia2))
{
Console.WriteLine("All is well!");
}
else if(currencyId == Dollar && (taxProfileId == TaxAmerica1 || taxProfileId == TaxAmerica2))
{
Console.WriteLine("All is well!");
}
else if (taxProfileId == 0)
{
Console.WriteLine("All is well!");
}
else
{
Console.WriteLine("Mismatch Detected!");
}
}
catch (Exception exception)
{
Console.WriteLine(exception.Message);
}
}
}
}
You can put all your valid combinations in a hashtable, i.e. IDictionary and go from there.
For example:
var validCombinations = new Dictionary<int, List<int>>();
validCombinations.Add(Rupee, new List<int> { TaxIndia1, TaxIndia2 });
validCombinations.Add(Dollar, new List<int> { TaxAmerica1, TaxAmerica2 });
int currencyId = int.Parse(args[0]);
int taxProfileId = int.Parse(args[1]);
List<int> validTaxes;
if (taxProfileId == 0 ||
(validCombinations.TryGetValue(currencyId, out validTaxes) &&
validTaxes.Contains(taxProfileId)))
{
Console.WriteLine("All is well!");
}
else
{
Console.WriteLine("Mismatch Detected!");
}
You could also populate the dictionary with combinations read from a database table, so you don't have to hardcode them. YMMV.
You can use a mapping dictionary of lists as an alternative
You could restructure your code like this:
So you just need to add to the validCurrencies Dictionary for each set of valid currency/tax profiles. Note that this is just to give you an alternative to writing 100 conditions, you will need to test and make the code robust yourself.
using System;
using System.Collections.Generic;
namespace MatchCondition
{
class MatchCondition
{
private enum TaxProfileEnum
{
Default = 0,
America1 = 100,
America2 = 200,
India1 = 300,
India2 = 400,
}
private enum CurrencyEnum
{
Rupee = 100,
Dollar = 200,
}
static void Main(string[] args)
{
try
{
Dictionary<CurrencyEnum, List<TaxProfileEnum>> validCurrencies = new Dictionary<CurrencyEnum, List<TaxProfileEnum>>()
{
{ CurrencyEnum.Rupee, new List<TaxProfileEnum>() { TaxProfileEnum.India1, TaxProfileEnum.India2 } },
{ CurrencyEnum.Dollar, new List<TaxProfileEnum>() { TaxProfileEnum.America1, TaxProfileEnum.America2 } },
};
CurrencyEnum currency = (CurrencyEnum)int.Parse(args[0]);
TaxProfileEnum taxProfile = (TaxProfileEnum)int.Parse(args[1]);
if (taxProfile == TaxProfileEnum.Default)
{
Console.WriteLine("All is well!");
return;
}
List<TaxProfileEnum> validTaxes;
if (validCurrencies.TryGetValue(currency, out validTaxes) && validTaxes.Contains(taxProfile))
{
Console.WriteLine("All is well!");
return;
}
Console.WriteLine("Mismatch Detected!");
}
catch (Exception exception)
{
Console.WriteLine(exception.Message);
}
}
}
}

Categories