How can I store a variable in an array - c#

I am trying to connect a "serial-code" or whatever to variable to be printed as a string. The code will be generated from 5 sensors and will give me a 5 digit number (sensorValue)(this calculation is not included in the example and I have simplified it to 3 digits). I add an "s" before the code so that I can make a variable with the same name. However I cannot seem to store a variable in the array as I get the message that the variables are assigned but is never used. It clearly cannot be attached the way i'm doing it at least. But I hope that I illustrates what I intend to do.
So I get the "serial-code" s123 but I need to convert it to another string. There will be approximately 3000 different "serial-codes" with a string attached to each one of them. I'm sure I can make 3000 "if" statements but I am afraid that would be very slow.
Any ideas how I can overcome this issue of mine?
Thanks in advance!
using System;
using System.Linq;
namespace TestingArray
{
static void Main(string[] args)
{
// Trying to assign a value to the string that is used in the array
var s123 = "Hello";
var s321 = "Bye";
var s111 = "Thanks";
// Creating the array to be used
object [] arr = { "s123", "s321", "s111" };
// A simulation of what the future sensor would read
int sensorValue;
sensorValue = 123;
// Creating a "code" with the sensorValue to find it in the array.
string doThis = "s" + sensorValue
;
// I want to display the string which corresponds to this "serial-code" string.
Console.Write(arr.Contains(doThis));
}
}

Sounds like you want a dictionary. The key is the name and the value is the sensor data.
static void Main(string[] args)
{
Dictionary<string, string> sensors = new Dictionary<string, string> {
{"s123", "Hello"},
{"s321", "Bye"},
{"s111", "Thanks"}
};
// A simulation of what the future sensor would read
int sensorValue;
sensorValue = 123;
// Creating a "code" with the sensorValue to find it in the array.
string doThis = "s" + sensorValue;
if (sensors.ContainsKey(doThis)) {
Console.WriteLine(sensors[doThis]);
}
}

Related

How can I find an Index in an array using a value that exists in another array and THAT array?

I have a c# class that looks like this:
public class MemberData
{
public int meme_ck;
public string meme_name;
public bool meme_active;
public MemberData(int ck2, string name2, bool active2)
{
meme_ck = ck2;
meme_name = name2;
meme_active = active2;
}
}
I have made two arrays out of that class:
private MemberData[] memarray1 = new MemberData[10000];
private MemberData[] memarray2 = new Memberdata[10000];
Over the course of my application I do a bunch of stuff with these two arrays and values change, etc. Member's name or active status may change which results in the ararys becoming different.
Eventually I need to compare them in order to do things to the other one based on what results are kicked out in the first one.
For example, member is de-activated in the first array based on something application does, I need to update array 2 to de-activate that same member.
I am trying to use some database design philosphy with the int CK (contrived-key) to be able to rapidly look up the entry in the other array based on the CK.
Since I can't figure it out I've had to resort to using nested for loops like this, which sucks:
foreach (Memberdata md in memarray1)
{
foreach (Memberdatamd2 in memarray2)
{
if (md.ck = md2.ck)
{
//de-activate member
}
}
}
Is there a better way to do this? I just want to find the index in the second array based on CK when I have the CK value from the first array.
Any other tips or advice you have about structure would be appreciated as well. Should I be using something other than arrays? How would I accomplish this same thing with Lists?
Thanks!
Should I be using something other than arrays?
Yes. Don't use arrays; they are seldom the right data structure to use.
How would I accomplish this same thing with Lists?
Lists are only marginally better. They don't support an efficient lookup-by-key operation which is what you need.
It sounds like what you want is instead of two arrays, two Dictionary<int, MemberData> where the key is the ck.
I totally agree with Eric Lippert's answer above. It is better you do not use Array.
Same thing can be achieved using List<MemberData>. You can use LINQ as well to query your DataStructure.
Following is one of the way just to achieve your result using array
class Program
{
static MemberData[] memarray1 = new MemberData[10000];
static MemberData[] memarray2 = new MemberData[10000];
static void Main(string[] args)
{
for (int i = 0; i < memarray1.Length; i++)
{
memarray1[i] = new MemberData(i + 1, "MemName" + i + 1, true);
memarray2[i] = new MemberData(i + 1, "MemName" + i + 1, true);
}
// SIMULATING YOUR APP OPERATION OF CHANGING A RANDOM ARRAY VALUE IN memarray1
int tempIndex = new Random().Next(0, 9999);
memarray1[tempIndex].meme_name = "ChangedName";
memarray1[tempIndex].meme_active = false;
//FOR YOUR UDERSTADNING TAKING meme_ck IN AN INTEGER VARIABLE
int ck_in_mem1 = memarray1[tempIndex].meme_ck;
//FINDING ITEM IN ARRAY2
MemberData tempData = memarray2.Where(val => val.meme_ck == ck_in_mem1).FirstOrDefault();
// THIS IS YOUR ITEM.
Console.ReadLine();
}
}

Array.ToString() returning System.Char[] c#

Im making a hangman game, at the start of the game the word that the player must guess is printed as stars. I have just started making it again after attempting to write it once and just having messy code that i couldn't bug fix. So I decided it best to write it again. The only problem is, when i try to get my array to print out by using array.ToString(); it just returns System.char[]. See below.
code:
class Program
{
static void Main(string[] args)
{
string PlayerOneWord;
string PlayerTwoGuess;
int lives = 5;
Console.WriteLine("Welcome to hangman!\n PLayer one, Please enter the word which player Two needs to guess!");
PlayerOneWord = Console.ReadLine().ToLower();
var stars = new char[PlayerOneWord.Length];
for (int i = 0; i < stars.Length ; i++)
{
stars[i] = '*';
}
string StarString = stars.ToString();
Console.Write("Word to Guess: {0}" , StarString);
Console.ReadLine();
}
}
output:
The output should say Word to guess: Hello.
Please will someone explain why this is happening as its not the first time I have run into this problem.
Calling ToString on a simple array only returns "T[]" regardless what the type T is. It doesn't have any special handling for char[].
To convert a char[] to string you can use:
string s = new string(charArray);
But for your concrete problem there is an even simpler solution:
string stars = new string('*', PlayerOneWord.Length);
The constructor public String(char c, int count) repeats c count times.
The variable stars is an array of chars. This is the reason you get this error. As it is stated in MSDN
Returns a string that represents the current object.
In order you get a string from the characters in this array, you could use this:
Console.Write("Word to Guess: {0}" , new String(stars));
The correct way to do this would be:
string StarString = new string(stars);
ToString() calls the standard implementation of the Array-class's ToString-method which is the same for all Arrays and similarily to object only returns the fully qualified class name.
Try this code:
static string ConvertCharArr2Str(char[] chs)
{
var s = "";
foreach (var c in chs)
{
s += c;
}
return s;
}

How to access individual fields within struct array

I'm trying to complete an assignment and I'm having trouble with the following (I have worked on this for the last 12 hours). Please help.
I have opened a file, saved the file into an struct array. Can access each element of the struct but don't know how I can access each individual field. i.e
Struct
//struct to hold the hand values
public struct CurrentHand
{
public char cardSuit;
public int cardValue;
}
I need to extract the cardValue into an array or variables so I can evaluate each record i.e. is the hand a pair or two pair etc. I have no idea how to do this. From what I have found its not possible to access each field, is this true?
//Open file and load data into array
public static void LoadHandData(CurrentHand[] handData, string fileName)
{
string input = ""; //temporary variable to hold one line of data
string[] cardData; //temporary array to hold data split from input
//Open the file and read the contents
StreamReader readHand = new StreamReader(fileName);
input = readHand.ReadLine(); //one record
cardData = input.Split(' '); //split record into fields
for (int counter = 0; counter < handData.Length; counter++)
{
handData[counter].cardSuit = Convert.ToChar(cardData[counter *2]);
handData[counter].cardValue = Convert.ToInt16(cardData[counter *2 +1]);
}
readHand.Close();
}
To obtain an array containing the values of the cards you hold in your hand, you can do:
var values = handData.Select(x=>x.cardValue).ToArray();
var seeds = handData.Select(x=>x.cardSuit).ToArray();
By the way, your struct should be called Card or something like that, since an Hand is supposed to be a collection of cards. The name you gave to it is just confusing and makes your code less readeable.
Your problem is not clear to me. anyway you can access invidual fields using .
try this...
CurrentHand.cardValue
using above you can get and set value for CurrentHand structure.

C#: Get an integer representation of a string array

I am new to C# and I ran into the following problem (I have looked for a solution here and on google but was not successful):
Given an array of strings (some columns can possibly be doubles or integers "in string format") I would like to convert this array to an integer array.
The question only concerns the columns with actual string values (say a list of countries).
Now I believe a Dictionary can help me to identify the unique values in a given column and associate an integer number to every country that appears.
Then to create my new array which should be of type int (or double) I could loop through the whole array and define the new array via the dictionary. This I would need to do for every column which has string values.
This seems inefficient, is there a better way?
In the end I would like to do multiple linear regression (or even fit a generalized linear model, meaning I want to get a design matrix eventually) with the data.
EDIT:
1) Sorry for being unclear, I will try to clarify:
Given:
MAKE;VALUE ;GENDER
AUDI;40912.2;m
WV;3332;f
AUDI;1234.99;m
DACIA;0;m
AUDI;12354.2;m
AUDI;123;m
VW;21321.2;f
I want to get a "numerical" matrix with identifiers for the the string valued columns
MAKE;VALUE;GENDER
1;40912.2;0
2;3332;1
1;1234.99;0
3;0;0
1;12354.2;0
1;123;0
2;21321.2;1
2) I think this is actually not what I need to solve my problem. Still it does seem like an interesting question.
3) Thank you for the responses so far.
This will take all the possible strings which represent an integer and puts them in a List.
You can do the same with strings wich represent a double.
Is this what you mean??
List<int> myIntList = new List<int>()
foreach(string value in stringArray)
{
int myInt;
if(Int.TryParse(value,out myInt)
{
myIntList.Add(myInt);
}
}
Dictionary is good if you want to map each string to a key like this:
var myDictionary = new Dictionary<int,string>();
myDictionary.Add(1,"CountryOne");
myDictionary.Add(2,"CountryTwo");
myDictionary.Add(3,"CountryThree");
Then you can get your values like:
string myCountry = myDictionary[2];
But still not sure if i'm helping you right now. Do you have som code to specify what you mean?
I'm not sure if this is what you are looking for but it does output the result you are looking for, from which you can create an appropriate data structure to use. I use a list of string but you can use something else to hold the processed data. I can expand further, if needed.
It does assume that the number of "columns", based on the semicolon character, is equal throughout the data and is flexible enough to handle any number of columns. Its kind of ugly but it should get what you want.
using System;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApplication3
{
class StringColIndex
{
public int ColIndex { get; set; }
public List<string> StringValues {get;set;}
}
class Program
{
static void Main(string[] args)
{
var StringRepresentationAsInt = new List<StringColIndex>();
List<string> rawDataList = new List<string>();
List<string> rawDataWithStringsAsIdsList = new List<string>();
rawDataList.Add("AUDI;40912.2;m");rawDataList.Add("VW;3332;f ");
rawDataList.Add("AUDI;1234.99;m");rawDataList.Add("DACIA;0;m");
rawDataList.Add("AUDI;12354.2;m");rawDataList.Add("AUDI;123;m");
rawDataList.Add("VW;21321.2;f ");
foreach(var rawData in rawDataList)
{
var split = rawData.Split(';');
var line = string.Empty;
for(int i= 0; i < split.Length; i++)
{
double outValue;
var isNumberic = Double.TryParse(split[i], out outValue);
var txt = split[i];
if (!isNumberic)
{
if(StringRepresentationAsInt
.Where(x => x.ColIndex == i).Count() == 0)
{
StringRepresentationAsInt.Add(
new StringColIndex { ColIndex = i,
StringValues = new List<string> { txt } });
}
var obj = StringRepresentationAsInt
.First(x => x.ColIndex == i);
if (!obj.StringValues.Contains(txt)){
obj.StringValues.Add(txt);
}
line += (string.IsNullOrEmpty(line) ?
string.Empty :
("," + (obj.StringValues.IndexOf(txt) + 1).ToString()));
}
else
{
line += "," + split[i];
}
}
rawDataWithStringsAsIdsList.Add(line);
}
rawDataWithStringsAsIdsList.ForEach(x => Console.WriteLine(x));
Console.ReadLine();
/*
Desired output:
1;40912.2;0
2;3332;1
1;1234.99;0
3;0;0
1;12354.2;0
1;123;0
2;21321.2;1
*/
}
}
}

Passing two arrays from one method to gather user info from another method C#

I'm not looking for specific code, rather, I'm looking for information and guidance. I want to learn but don't really want someone to code it.
I am looking in how to pass two arrays to a different method so they can be filled with user input. I can't seem to figure this out and I have researched various sites as well as my text and lectures and can't find the required techniques to do this. I know how to pass one array to a different method for processing (IE getting avg/sum etcetc) but not how to fill two arrays from one seperate method. Any guidance and information would be greatly appreciated. This is what I've got so far, or rather, what I'm left with. I got the other methods fairly done over, just need this part to move onto the debugging phase.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace PhoneDial
{
class Program
{
// Get player names and their scores and stores them into array for an unknown number of players up to 100
static void InputData(string[] nameList, int[]playerScore)
{
string userInput;
int count = 0;
do
{
Console.Write("\nEnter a players name: ");
userInput = Console.ReadLine();
if (userInput != "Q" && userInput != "q")
{
nameList[0] = Console.ReadLine();
++count;
}
else break;
Console.WriteLine("Enter {0}'s score:", userInput);
playerScore[0] = Convert.ToInt32(Console.ReadLine());
} while (userInput != "Q" && userInput != "q");
}
//Declare variables for number of players and average score and two arrays of size 100 (one for names, one for respective scores
//Calls functions in sequence, passing necessary parameters by reference
//InputData(), passing arrays and number of players variable by reference
//DisplayPlayerData(), passing arrays and number of players by reference
//CalculateAverageScore(), passing arrays and number of players by reference. Store returned value in avg variable
//DisplayBelowAverage(), passing arrays and number of players variable by reference, passing average variable by value
static void Main(string[] args)
{
string[] nameList = new string[100];
int[] playerScore = new int[100];
int count = 0, avg = 0;
InputData(nameList, playerScore);
}
Your question is not entirely clear, but from what I understand, to declare an array in a method and pass to another method to be filled, you just need:
public void MethodA()
{
string[] stringArray = new string[100];
MethodB(stringArray);
}
public void MethodB(string[] stringArray)
{
// Fill the array
stringArray[0] = "Hello";
// ...
}
If, however, you wish to pass some variable reference to a method to then have that method create the array and fill it, you will want to use the ref keyword (as you have with standard variables) on an array variable. Like so:
public void MethodA()
{
string[] stringArray;
MethodB(ref stringArray);
// Array is now created and filled
}
public void MethodB(ref string[] stringArray)
{
// Create the array
stringArray = new string[100];
// Fill the array
stringArray[0] = "Hello";
// ...
}
To do either of these two approaches with two arrays is the same, but with an added parameter. i.e.:
public void MethodB(string[] array1, int[] array2) { }
public void MethodB(ref string[] array1, ref int[] array2) { }
Use Dictionary instead of array.
Dictionary<string, int> Results = new Dictionary<string, int>();
http://msdn.microsoft.com/en-us/library/x525za90%28v=vs.110%29.aspx
You can make the variables nameList and playerScore global by putting them under the class Program{ (dont forget to make the variables static and make lists of them).
then in your InputData use the .add method to add aditional values to the two variables.
Maybe it is also a good idea to use a dictionary instead of two arrays.
I hope this helped

Categories

Resources