我正在使用c#
我的变量中有以下字符串。
string results = "Mr,Mike,Lewis,32,Project Manager,India";
现在我想在会话变量的Dictionary类型中添加这些值。我在代码中声明了一个dict类型变量。
Dictionary<string, string> skywardsDetails = new Dictionary<string, string>();
立即写下我编写的代码如下:
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)
}
}
请建议
答案 0 :(得分:5)
您的CSV results
变量不代表字典。它代表Employee
模型:
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; }
}
然后:
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
}
答案 1 :(得分:1)
你不能在这里真正使用foreach而不是声明局部变量用
替换该部分 skywardsDetails["title"] = array[0];
skywardsDetails["firstname"] = array[1];
skywardsDetails["lastname"] = array[2];
skywardsDetails["age"] = array[3];
skywardsDetails["designation"] = array[4];
skywardsDetails["country"] = array[5];
现在将这些字符串常量移动到某个常量,如const string Title =“title”,您将能够从字典中获取所需的字段数据,如
string title= skywardsDetails[Constants.Title]
答案 2 :(得分:1)
使用这样的词典会更有意义:
skywardsDetails.Add("Title", array[0]);
skywardsDetails.Add("FirstName", array[1]);
// etc.
您不应该使用实际值作为键,因为我认为您需要一种通用的方式来访问它们。
答案 3 :(得分:0)
尝试这样的事情:
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];
}