Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I'am trying to input som Flight information to Dictionary C# console.
But I don't know how to add those to my Dictionary.I want to store by flight number (I want flight number as a KEY). Here is my class and the hole code
public class Flight
{
public int FlightNr;
public string Destination;
}
int FlNr;
string FlDest;
List<Flight> flightList = new List<Flight>();
do
{
Console.Write("Enter flight nummer (only numbers) :");
FlNr = int.Parse(Console.ReadLine());
Console.Write("Enter destination :");
FlDest = Console.ReadLine();
flightList.Add(new Flight() { FlightNr = FlNr, Destination = FlDest });
} while (FlNr != 0);
// create Dictionary
Dictionary<int, Flight> dictioneryFlight = new Dictionary<int, Flight>();
// My question is How to add those flights in my Dictionary ?
dictioneryFlight.Add( I don't know what to input here);
Or is something wrong with my other code? something I missed? Thank you in advance! .
If you want to use the number as key for your dictionary then you don't need a list of flights but you can use directly the dictionary
Dictionary<int, Flight> dictioneryFlight = new Dictionary<int, Flight>();
do
{
Console.Write("Enter flight nummer (only numbers) :");
// Always check user input, do not take for granted that this is an integer
if(Int32.TryParse(Console.ReadLine(), out FlNr))
{
if(FlNr != 0)
{
// You cannot add two identical keys to the dictionary
if(dictioneryFlight.ContainsKey(FlNr))
Console.WriteLine("Fly number already inserted");
else
{
Console.Write("Enter destination :");
FlDest = Console.ReadLine();
Flight f = new Flight() { FlightNr = FlNr, Destination = FlDest };
// Add it
dictioneryFlight.Add(FlNr, f);
}
}
}
else
// This is needed to continue the loop if the user don't type a
// number because when tryparse cannot convert to an integer it
// sets the out parameter to 0.
FlNr = -1;
} while (FlNr != 0);
If you want to create a dictionary out of your list of flights, you can use ToDictionary().
var dict = flightList.ToDictionary(f => f.FlightNr);
You can do it without LINQ like so:
var dict = new Dictionary<int, Flight>();
foreach (var flight in flightList)
dict.Add(flight.FlightNr, flight);
As others have mentioned, you can skip having a List<Flight> altogether and just add directly to the dictionary when they're created instead.
One thing you might want to consider is checking if FlNr is 0 right after you parse the user input and break out of the loop right away if it is. Otherwise you'll end up with flight information for flight number 0 in your list/dictionary.
Not absolutely sure but I think you meant to store by flight number like
//declare this before your loop starts
Dictionary<int, Flight> dictioneryFlight = new Dictionary<int, Flight>();
//Add to dictionary in your loop
dictioneryFlight.Add(FlNr, new Flight() { FlightNr = FlNr, Destination = FlDest });
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
Highest Salary in Dept
I have to read data from given below data from input file
The input is being read in from a file called input.txt in this format:
22,Rajan Anand,Engineering,1600000
23,Swati Patil,Testing,800000
27,Vijay Chawda,Engineering,800000
29,Basant Mahapatra,Engineering,600000
32,Ajay Patel,Testing,350000
34,Swaraj Birla,Testing,350000
Each line consists of 4 fields
"Employee ID," "Name," "Department," and "Salary."
Here, "Employee ID" and "Salary" are integers, while "Name" and "Department" are strings that do not contain commas or newlines.
Currently, below program reads the input and creates an array of String from the lines of input. Then it calls a method processData on with this array, and prints the returned data to the output file.
Unfortunately, processData currently does not do anything useful - it just returns an empty Dictionary<String,int>.
I have to modify processData find the Employee IDs of the highest paid employee in each department. Specifically, processData should return a dictionary where each key is the name of a department,and the value is the Employee ID of the employee in that department who has the highest salary.
In case multiple employees in a department are tied for the highest salary, you can pick any one of them.
Engineering: 22
Testing: 23
Sample program
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace ProgramNamespace
{
public class Program
{
public static Dictionary<String, int> processData(IEnumerable<string> lines)
{
Dictionary<String, int> retVal = new Dictionary<String, int>();
return retVal;
}
static void Main(string[] args)
{
try
{
Dictionary<String, int> retVal = processData(File.ReadAllLines("input.txt"));
// code to write in output file
}
catch (IOException ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
I have an idea:
create an Class name "EmployeeSalary"(or other name you like)
parse all lines into List< EmployeeSalary > (use split, and create new object)
use linq to query List< EmployeeSalary >(group by department and find max salary)
generate query result to dictionary you want.
If you are familiar with linq, that would be much easier to get the idea.
public Dictionary<String, int> processData(IEnumerable<string> lines)
{
List<EmployeeSalary> list = new List<EmployeeSalary>();
foreach(var line in lines)
{
string[] temp = line.Split(',');
EmployeeSalary tempObj = new EmployeeSalary();
tempObj.EmployeeID = int.Parse(temp[0]);
tempObj.Name = temp[1];
tempObj.Department = temp[2];
tempObj.Salary = int.Parse(temp[3]);
list.Add(tempObj);
}
var query = (from f in list group f by f.Department into g select g);
Dictionary<String, int> retVal =
query.ToDictionary(x => x.Key, x => x.OrderByDescending(c=>c.Salary).Select(c=>c.EmployeeID).FirstOrDefault());
return retVal;
}
You could do it as following if you want to do it with Dictionary<string,int>. the Crux of idea is to create an intermediate list comprising of all Employees and then Group them by Department, before Ordering By Salary(desc) and taking the first one.
public static Dictionary<String, int> processData(IEnumerable<string> lines)
{
Dictionary<String, int> retVal = new Dictionary<String, int>();
var list = new List<Employee>();
foreach(var user in lines)
{
var userDetails = user.Split(new []{','},StringSplitOptions.RemoveEmptyEntries);
list.Add(new Employee
{
Id=int.Parse(userDetails[0]),
UserName = userDetails[1],
Department = userDetails[2],
Salary = int.Parse(userDetails[3])
});
}
retVal = list.GroupBy(x=>x.Department).Select(x=>x.ToList()
.OrderByDescending(c=>c.Salary).First())
.ToDictionary(x=> x.Department, y=> y.Id);
return retVal;
}
Where Employee is defined as
public class Employee
{
public int Id;
public string UserName;
public int Salary;
public string Department;
}
Output
I managed to create an input field that is able to be checked and verified upon a question via creating another text field and linking that to said question, so for example if the value of the question was '1', the answer would be '1'. Then I made a text comparison, so that if what the user wrote = that text field the answer would be correct.
However, I realise that sometimes someone can write something else. For example in the question ' What do you think about tigers', there isn't just one possible answer. And therefore, the way I did that for the input field does not exactly work (does it?).
I did quite a lot of research and found out about dictionaries, but since they only have one key value that wouldn't help, and then I found out about lists, which might?
So my question is whether it is possible, and how, to create a list that's integer values is somehow linked to the values of the overarching question, so that if the random value is 1, the list value is 1 as well, and then check if what is written matches any of the answers with that random value.
If what I just said didn't make sense, here's an example:
Current behavior:
SURVEY: Do you like cats?
INPUT FIELD: Yes I do
HIDDEN TEXT FIELD : Yes I do
input field = hidden text field and therefore correct
Ideal behavior:
SURVEY: Do you like cats?
INPUT FIELD: I do like cats
POSSIBLE ANSWERS: I do like cats, Yes I do etc.
INPUT FIELD contains an answer in the list which matches the question and therefore correct.
I thought you could use the .Contains function, but I didn't know how to link it all together.
EDIT:
I tried to solve this problem via the creation of a dictionary and searching for a key (which I believe was the right way to do this), but for some reason this code doesn't even work when checking it? (it's like the .containsKey function doesn't work?)
public string questions = "hi;weird;by";
Dictionary<int, string> tester = new Dictionary<int, string>();
// Use this for initialization
void Start ()
{
tester.Add(1, questions);
tester.Add(2, "hello");
tester.Add(3, "by");
tester.Add(4, "hi");
tester.Add(5, "bye");
}
// Update is called once per frame
void Update ()
{
}
public void hello ()
{
if(tester.ContainsKey(2))
{
string value = tester[2];
Debug.Log("Correct");
}
}
EDIT 1:
Following what trashr0X said I tried doing it by having a dictionary script in the main camera and a script in the inputfield, but for some reason when I load it nothing works on the console:
LIST
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System.Linq;
public class Listpractice : MonoBehaviour
{
Dictionary<int, List<string>> tester = new Dictionary<int, List<string>>();
List<string> possibleAnswersToQuestionZero = new List<string>();
// Use this for initialization
void Start () {
possibleAnswersToQuestionZero.Add("Hello");
possibleAnswersToQuestionZero.Add("By");
tester.Add(0, possibleAnswersToQuestionZero);
}
// Update is called once per frame
void Update ()
{
}
public void hello ()
{
var toCheck = tester[0].FirstOrDefault(x => x == GameController.hello);
if (toCheck != null)
{
Debug.Log("Hi!");
}
}
}
INPUT FIELD
public class QAClass07
{
public string Answer = "";
public string Question = "";
QAClass07 result = new QAClass07();
}
public static string hello;
void Start()
{
GameObject a = gameObject;
hello = a.transform.Find("Text").GetComponent<Text>().text;
}
// registers what the user writes
public void getInput(string guess)
{
// Does something assuming someone enters something
if (GetComponent<InputField>() != null)
{
hello = GetComponentInChildren<Text>().text;
}
}
Simply use Dictionary<int, List<string>> and then add all the answers to the corresponding question id.
var questions = new List<string> { "hi", "weird", "by" };
var tester = new Dictionary<int, List<string>>();
// Use this for initialization
void Start ()
{
tester.Add(1, questions);
tester.Add(2, new List<string> { "hello" });
tester.Add(3, new List<string> { "by" });
tester.Add(4, new List<string> { "hi" });
tester.Add(5, new List<string> { "bye" });
}
public void hello ()
{
if(tester.ContainsKey(2))
{
var answers = tester[2] ?? new List<string>();
// now you have all answers linked to question with id 2 in answers variable
}
}
"I did quite a lot of research and found out about dictionaries, but since they only have one key value that wouldn't help, and then I found out about lists, which might?"
Yes, a Dictionary<TKey, TValue> does comprise of key-value pairs of a particular type each; you can declare the type of it's key to be int (corresponding to the index of the question currently asked), and declare the type of it's value to be List<string>, to hold possible answers for that question.
// key is question index, value is a list of possible answers for that question
var dictionary = new Dictionary<int, List<string>>();
// list of possible answers for question 0 (random question number chosen for the example)
var possibleAnswersToQuestionZero = new List<string>();
possibleAnswersToQuestionZero.Add("Possible Answer to question 0");
possibleAnswersToQuestionZero.Add("Another possible answer to question 0");
// add that list to the dictionary at key 0.
// you should be also checking if the key exists before trying to access it's value,
// and what happens if the list returned for that key is null or empty.
dictionary.Add(0, possibleAnswersToQuestionZero);
To check if the answer submitted by the user (let's assume it is saved in a variable named userInput) for question 0 is in the list of possible answers for that key, we would do:
// check if the list at dictionary[0] has at least one instance of userInput,
// otherwise return null
var toCheck = dictionary[0].FirstOrDefault(x => x == userInput);
// if the result is not null, the answer was found
if (toCheck != null)
{
// answer found
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
Have 5 Names and 5 number.
Giv name need number.
better way?
string name = "Mark";
int x;
if(name == "John")
{
x = 1;
}else if(name == "Jimy"){
x = 2;
}else if(name == "Mark"){
x = 3;
}.... etc
return x;
result is x=3.
Often if you have a unique list of items that you want to associate with some other item, a Dictionary is a good solution. Each item in a dictionary is called a KeyValuePair, and consists of two parts: a unique key, which in this case would be the name, and a value associated with that key, which in this case is an int.
For your example, it would look something like:
// The part in parenthesis specifies that the keys will be
// case-insensitive when doing comparisons, so you can search
// for "john", "John", or "JOHN", and get the same value back
private static Dictionary<string, int> nameValues =
new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase)
{
{"John", 1},
{"Jimmy", 2},
{"Mark", 3}
};
And a method for retrieving the int value for a name might look like:
private static int GetIntForName(string name)
{
var valueIfNotFound = -1;
return nameValues.ContainsKey(name) ? nameValues[name] : valueIfNotFound;
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I'm starting to write a downloader.. But I want to put the files that need to extract, are required, or option in a list for later reference by the downloader.
A sample string that is fed into it would be like this:
file0.txt:0 file1.txt:0 file2.txt:1 file3.txt:2 file4.txt:2 file5.txt:2
What i want to do, is get an output like this:
Extract: file0.txt file1.txt
Required: file2.txt
Optional: file3.txt file4.txt, file5.txt
But I have no clue how to go about doing this.
The downloader will use these lists to download files the external app needs.
I'm assuming that the numbers that come after each file name are supposed to indicate what kind of file they are?
Now you definitely should try to solve this problem yourself - because thats how you learn, but here is a fairly elegant LINQ solution that creates an output identical to the example you posted.
// Define this in your class
enum FileType : byte
{
Extract = 0,
Required = 1,
Optional = 2,
}
static void Main(string[] args)
{
string input = "file0.txt:0 file1.txt:0 file2.txt:1 file3.txt:2 file4.txt:2 file5.txt:2";
// create list of files
var list = input.Split(' ').Select(file =>
{
var spl = file.Split(':');
var type = (FileType)Enum.Parse(typeof(FileType), spl[1]);
return new { Name = spl[0], Type = type };
}).ToArray();
// group by type and write to console
var group = list.GroupBy(l => l.Type);
foreach (var g in group)
{
Console.WriteLine("{0}: {1}", g.Key, String.Join(",", g.Select(a => a.Name)));
}
}
What you could do is two string split operations on the string you're fed.
var input = "file0.txt:0 file1.txt:0 file2.txt:1 file3.txt:2 file4.txt:2 file5.txt:2";
// gets each pairing
var filePairs = input.split(new[] {' '});
foreach(var filePair in filePairs)
{
var fileInfo = filePair.split(new[] {';'}); // [file0.txt, 0]
var fileName = fileInfo[0]; // file0.txt
var fileKeep = fileInfo[1]; // 0, 1, or 2.
}
From here you can do what you wish with the info you have in the foreach loop. And you can add the info to a list for storing it.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have a string of the format "Position=10,IntraDay=20,Client=30,". I want to insert it into a dictionary e.g ,, should be my key value pair of the dictionary. How to do it in an easy way .And vice versa too.
Pseudo-code, since you can surely figure the exact steps out yourself:
dict ← new Dictionary〈string, string〉
parts ← split input at ','
for each part in parts:
key, value ← split part at '='
add (key, value) to dict
That'd be the most trivial way. It's not necessarily efficient, it may break, depending on your data, but since we don't know anything else here, it might just as well work. You could also make the dictionary accept int values and parse the integer beforehand.
This is an example code of #Joey 's Pseudo-code:
//Your string (note: I have removed ending comma of your sample string)
string mystring = "Position=10,IntraDay=20,Client=30";
//Your dictionary
Dictionary<string, string> mydic = mystring.Split(',')
.ToDictionary(s => s.Split('=')[0],
s => s.Split('=')[1] );
private Dictionary<String, Int32> ProcessInputString(string str) {
var Dictionary = new Dictionary<String, Int32>();
var Entries = str.Split(',', StringSplitOptions.RemoveEmptyEntries);
foreach(var Entry in Entries) {
var EntryData = Entry.Split('=', StringSplitOptions.RemoveEmptyEntries);
var Key = EntryData[0];
var Value = Convert.ToInt32(EntryData[1]);
if(!Dictionary.ContainsKey(Key))
Dicationary[Key] = Value;
}
return Dictionary;
}
Go for the following:
var dic = new Dictionary<string,int>();
var Pairs = "Position=10,IntraDay=20,Client=30,".Split(',', StringSplitOptions.RemoveEmptyEntries);
foreach (var pair in Pairs)
{
var p = pair.Split('=');
dic.Add(p[0],Convert.ToInt32(p[1]));
}
Hope it helps!