首先,我有一个遍历用户字典的 foreach 循环。'int' 值是一个订单列表(“ControlNumber”)。
foreach (KeyValuePair<string, int> e in errorOrders)
{
//finds error percentage for user
errPercentage = GetErrPercentage(e.Key);
Console.WriteLine("Percentage of errors for " + e.Key + ": " + Math.Round(errPercentage, 2) * 100 + "%");
//finds orderPerHour for user
ordersPerHour = OrdersPerHour(e.Key);
//Selects random orders for user based on errPercentage, saves to DT "randomOrders"
RandomOrders = RandomSelect(errPercentage, e.Key);
Console.WriteLine("Number of orders pulled : " + RandomOrders.Rows.Count);
//Print out orders randomly collected
for (int i = 0; i < RandomOrders.Rows.Count; i++)
{
Console.WriteLine(RandomOrders.Rows[i]["ControlNumber"]);
}
Console.WriteLine("\r\n");
//Creates class and fills class for each user
FillUserListClass(RandomOrders);
}
下面的部分是 FillUserListClass 函数。这就是我的麻烦发生的地方。现在,我在下面函数的最后一行收到一个错误(“对象引用未设置为对象的实例。”)。它尝试将“ControlNumber”添加到 UserList[username] 类。
现在,我愿意接受有关更改此功能的建议。本质上,我想为每个用户创建一个类,并在这个类中保存一个包含每个用户的“ControlNumbers”的列表。
我有人尝试用 LINQ 来做这件事,但因为那东西在我头顶上,我无法解决它。(如果你认为这是最好的方法,我也会把 LINQ 代码放在这里)
public static void FillUserListClass(DataTable dt)
{
Dictionary<string, List<int>> UserList = new Dictionary<string, List<int>>();
{
foreach (DataRow row in dt.Rows)
{
object value = row["ControlNumber"];
if (value == DBNull.Value)
{
row.Delete();
}
}
for (int ctr = 1; ctr <= dt.Rows.Count; ctr++)
{
var row = dt.Rows[ctr];
var userName = row["User"].ToString();
if (UserList.ContainsKey(userName))
{
UserList[userName].Add(Convert.ToInt32(row["ControlNumber"]));
}
else
{
UserList.Add(row["User"].ToString(), null);
UserList[userName].Add(Convert.ToInt32(row["ControlNumber"]));
}
}
}
如果您需要,这是我要填写的用户类
public class User
{
private string _name;
public string UserName { get; set; }
public List<int?> ControlNumber { get; set; }
public User (string username)
{
_name = username;
}
public User()
{
}
}