I am using c#
I have got below string in my variable.
string results = "Mr,Mike,Lewis,32,Project Manager,India";
Now I want to add these values in Dictionary type of session variable. I have declared a dict type variable in my code.
Dictionary<string, string> skywardsDetails = new Dictionary<string, string>();
Write now what I have written code was like below:
if (!string.IsNullOrEmpty(results))
{
string[] array = results.Split(',');
string title = array[0];
string firstname = array[1];
string lastname = array[2];
string age = array[3];
string designation = array[4];
string country = array[4];
//Here I want to write the new code which will add the results.Split(',') values in my Session variable as a Dictionary type.
foreach (string key in results.Split(','))
{
skywardsDetails.Add(key,//What to do here)
}
}
Please suggest
Your CSV results
variable doesn't represent a dictionary. It represents an Employee
model:
public class Employee
{
public string Title { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
public string Designation { get; set; }
public string Country { get; set; }
}
and then:
var tokens = (results ?? string.Empty).Split(',');
if (tokens.Length > 5)
{
var employee = new Employee
{
Title = tokens[0],
FirstName = tokens[1],
LastName = tokens[2],
Age = int.Parse(tokens[3]),
Designation = tokens[4],
Country = tokens[5]
};
// TODO: do something with this employee like adding it
// to some dictionary, session, whatever
}
You cant really use foreach here and instead of declaring local variables replace that part with
skywardsDetails["title"] = array[0];
skywardsDetails["firstname"] = array[1];
skywardsDetails["lastname"] = array[2];
skywardsDetails["age"] = array[3];
skywardsDetails["designation"] = array[4];
skywardsDetails["country"] = array[5];
Now move those string constants to some constant like const string Title="title" and you will be able to get required field data from your dictionary like
string title= skywardsDetails[Constants.Title]
It would make more sense to use the dictionary like this:
skywardsDetails.Add("Title", array[0]);
skywardsDetails.Add("FirstName", array[1]);
// etc.
You shouldn't use the actual values as keys, as i think you want a generic way to access them.
Try something like this:
enum UserData
{
Title,
Firstname,
Lastname,
Age,
Designation,
Country
}
//========================================================
string results = "Mr,Mike,Lewis,32,Project Manager,India";
string[] array = results.Split(',');
var skywardsDetails = new Dictionary<UserData, string>();
// maybe you need some check data here
for (int i = 0; i < array.Length; i++)
{
skywardsDetails[(UserData)i] = array[i];
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.