Dynamic Class identifier based on variable - c#

I have the following function below that I'm trying to make and fill a class called User.
I want the Class Identifier to be dynamically named for each user there is.
The datatable that is being passed in contains informations like below.
USER | CONTROLNUMBER
"jsmith" | "789842"
I want to make a class named "JSmith" and fill the properties in that class accordingly.
I am extremely new to using classes in useful way, so be gentle.
public static void FillUserListClass(DataTable dt, string _userName)
{
User _userName = new User();
_userName.ControlNumber = "789842";
_userName.UserName = "jsmith";
}

Would something like this be right for the dictionary of list idea?
static Dictionary<string, List<int>> UserList = new Dictionary<string, List<int>>();
public static void FillUserListClass(DataTable dt)
{
for (int ctr = 0; 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(), new List<int>());
UserList[userName].Add(Convert.ToInt32(row["ControlNumber"]));
}
}
And if so, how would i print out the dictionary so you would see something similar to
'jsmith' has 4 control numbers.
"234950"
"494602"
"494200"
"585890"

Related

Initializing string array for data reference [duplicate]

This question already has answers here:
Meanings of declaring, instantiating, initializing and assigning an object
(2 answers)
Closed 6 years ago.
What I'm trying to do with this is save a list of reference keys for everything that is populating a listbox. There will be an unknown quantity of lines(users/"patients"). After saving the list, I want to be able to use the listbox index to find the corresponding key, and use that to move on to the next part.
public partial class PatientList : Window
{
HumanResources ListAllPatients;
List<PatientInformation> AllPatients;
string[] Usernames;
public PatientList()
{
InitializeComponent();
int i = 0;
string[] Usernames = new string[i];
ListAllPatients = new HumanResources();
AllPatients = ListAllPatients.PopPatientList();
foreach (PatientInformation PatientChoice in AllPatients)
{
Usernames[i] = PatientChoice.Username;
lboxPatients.Items.Add(string.Format("{0} {1}; {2}", PatientChoice.FirstName, PatientChoice.LastName, PatientChoice.Gender));
i += 1;
}
}
Here is the code for the button that moves you on to the next section
public void btnSelectPatient_Click(object sender, RoutedEventArgs e)
{
PatientInfo PatientInfoWindow = new PatientInfo();
PatientInfoWindow.Show();
//i = lboxPatients.SelectedIndex;
//UserFactory.CurrentUser = Usernames2[i];
this.Close();
}
My issue is this: I believe I've initialized a string array to do this, but VS keeps telling me it isn't assigned to, and will always remain null.
My question: How and where do I properly initialize a string array (or something better) in order to accomplish sending the key from PatientList() to btnSelectPatient?
You are not initializing the string[] field but a local variable in the constructor here:
string[] Usernames;
public PatientList()
{
InitializeComponent();
int i = 0;
string[] Usernames = new string[i];
You have to assign this array to the field:
public PatientList()
{
InitializeComponent();
int i = 0;
this.Usernames = new string[i];
But that doesn't make much sense currently because it's length is always 0.
Maybe you want this instead:
public PatientList()
{
InitializeComponent();
ListAllPatients = new HumanResources();
AllPatients = ListAllPatients.PopPatientList();
this.Usernames = new string[AllPatients.Count];
int i = 0;
foreach (PatientInformation PatientChoice in AllPatients)
{
Usernames[i] = PatientChoice.Username;
lboxPatients.Items.Add(string.Format("{0} {1}; {2}", PatientChoice.FirstName, PatientChoice.LastName, PatientChoice.Gender));
i += 1;
}
}
You have a few mistakes:
Your initializing a new local variable instead of the class-level variable because you declare it again (string[] userNames = ...
Your initializing an array of length 0. This will fail when you try to add items to position 1 and above.
My advice would be to use a List, as it's better suited for dynamic length lists and you don't need to keep track of the index yourself, it will automatically be added at the right index:
HumanResources ListAllPatients;
List<PatientInformation> AllPatients;
List<string> Usernames = new List<string>();
public PatientList()
{
InitializeComponent();
ListAllPatients = new HumanResources();
AllPatients = ListAllPatients.PopPatientList();
foreach (PatientInformation PatientChoice in AllPatients)
{
Usernames.Add(PatientChoice.Username);
lboxPatients.Items.Add(string.Format("{0} {1}; {2}", PatientChoice.FirstName, PatientChoice.LastName, PatientChoice.Gender));
}
}

how set value in dictionary when content a dictionary and class

I defined the variable below:
Dictionary<clssMenu_Item, Dictionary<clssMenu_Item, List<clssMenu_Item>>> dicMenu =
new Dictionary<clssMenu_Item, Dictionary<clssMenu_Item, List<clssMenu_Item>>>();
The type clssMenu_Item is defined as:
class clssMenu_Item
{
public string name;
public string text;
}
I have a string (I call strKey) already assigned to the text property of clssMenu_Item inside dicMenu. It's clear text is part of key. I want to search dicMenu to find value of strKey in all over of dictionary such as its sub. I don't know how can get this value?!
this method calculates the key of the dictionary:
private List<clssMenu_Item> GetFormButtons(Form form)
{
List<clssMenu_Item> ListBtn = new List<clssMenu_Item>();
foreach (Control c in GetAllControls<Button>(form))
{
int btnIndex= c.Name.IndexOf("btn");
if (btnIndex != 0) // find all of the determined buttons
{
clssMenu_Item objBtn = new clssMenu_Item();
objBtn.name = c.Name.ToString();
objBtn.text = c.Text;
ListBtn.Add(objBtn);
}
}
return ListBtn;
}
here is how I populate the key:
foreach (var k in objH.mainForm) //fill dicMenu
{
dicMenu.Add(k,null);
}
The reason that I'm using a nested dictionary is that this tree has only 3 levels. Each clssMenu_Items has a group of children like itself type. dictionary was my solution to save them.
problem:
now I wanna fill value of keys by below code:
Dictionary<clssMenu_Item, List<clssMenu_Item>> d2 = new Dictionary<clssMenu_Item, List<clssMenu_Item>>();
clssMenu_Item k = new clssMenu_Item();
k.text = strKey;
foreach(var prp in dicMenu.Keys) //we should fill all of the variables in class
{
if (prp.text == strKey)
{ k.name = prp.name; break; }
}
d2= dicMenu[k]; //assign value of key
I dont know why I have error on d2= dicMenu[k]; said k is not in DicMenu, although I debug this block. we have k in DicMenu :( I dont know what should I do?!
is there other way to create a tree?

Filling a DataGridView with a List<List<String>>()

This question may be hard to explain. I'm writing a C# VS 2012 WinForms application that involves me getting data from one list and putting that into a list with columns. I have a,
public List<List<string>> allRows = new List<List<string>>();
to allow for the list without columns to be put into columns, here is the code that does that,
//LOOP THAT PUTS LIST INTO COLUMNS
for (int i = 0; i < fullData.Count; i++)
{
if (i % 6 == 0)
allRows.Add(new List<string>());
allRows.Last().Add(fullData[i]);
}
// final result giving me answers in columns
string path = String.Format("C:\\Users\\sackermann\\Desktop\\result.txt");
File.WriteAllLines(path, allRows.Select(row => string.Join(" ", row)));
I was wondering if there was anyway I could possible put each of the columns of the List<List<String>> into a DataGridView?
If you had a class with the properties defined in it, and then have a List<customClass> then it would be simple. Plus it defines the column names for you. Not sure if that is feasible in your situation.
public class foo
{
public string foo1 {get;set;}
public string foo2 {get;set;}
}
public Form1()
{
InitializeComponent();
var foo = new foo() ;
foo.foo1 = "some";
foo.foo2 = "text";
List<foo> _foo = new List<foo>();
_foo.Add(foo);
dgv.DataSource = _foo;
}

Sending a list of doubles as strings to the database

Just quite confused with the piece of code below.
I have class like below
public class Counter
{
public Double NormalCounter { get; set; }
public Double SATCounter { get; set; }
public Double SUNCounter { get; set; }
}
in my main class i have method to do some calculation to fill the counter
Counter CountHrs = GetBookedHours(resourceBkg, PrevEvent);
var lstExpResult = new List<string> {CountHrs.NormalCounter.ToString(),
CountHrs.SATCounter.ToString(),
CountHrs.SUNCounter.ToString()};
UpdateBooking(bookingSesid, lstExpResult);
Just assume i have the value like below in the counter
NormalCounter =4
SATCounter=10
SUNCounter=6
am trying to add in to string list and update the database.is that the right way to do ? or any other options i have please.
my update booking method is below to give clear idea.
public static bool UpdateBooking(string BookingSesid,List<string>HoursByRate)
{
SchedwinEntities db = new SchedwinEntities();
string value = string.Empty;
for (int i = 0; i < 5; i++)
{
string str = " ";
if (i < HoursByRate.Count())
{
str = HoursByRate[i];
value += str + ((char)13).ToString() + ((char)10).ToString();
}
}
var query =
from SEVTs in db.SEVTs
where
SEVTs.SESID.Trim() == BookingSesid//SESID
select SEVTs;
foreach (var SEVTs in query)
{
SEVTs.USER3 = value;//value
}
try
{
db.SaveChanges();
return true;
}
catch (UpdateException ex)
{
return false;
}
}
Rather than passing a list of strings that represent doubles, you should pass a list of key-value pairs, construct a parametersized statement from them, and use the list of key-value-pairs to bind parameter values, like this:
class SqlParamBinding {
string Name {get;set;}
object Value {get;set;}
}
var lstExpResult = new List<SqlParamBinding> {
new SqlParamBinding { Name = "NormalCounter", Value = CountHrs.NormalCounter}
, new SqlParamBinding { Name = "SATCounter", Value = CountHrs.SATCounter}
, new SqlParamBinding { Name = "SUNCounter", Value = CountHrs.SUNCounter}
};
UpdateBooking(bookingSesid, lstExpResult);
Now that lstExpResult separates names from values, your UpdateBooking code could format the SQL expression as
WHERE NormalCounter=#NormalCounter AND SATCounter=#SATCounter AND ...
and then bind #NormalCounter, #SATCounter, and #SUNCounter to the values passed in the lstExpResult list.
If it is going to list of Counter classes then have List instead of List. Looks like you might be having bunch of Counter objects that might be getting updated or sent to the database.
Counter c = new Counter();
c. NormalCounter = 4
c.SATCounter = 10
c.SunCounter = 10
List<Counter> listCounter = new List<Counter>
listCounter.Add(c);
Code is more maintainable and readable.
If you are sending one object at a time, then no need of list at all. You can pass in the counter object to your UpdateMethod and parse it while updating the database.

Create list<string> dynamically

I want to create a list in a button click event...every time the button is clicked a new list should be created having different name than the previous one...
Can anyone please help me out...I'm stuck on it...
Better create List<List<string>>
List<List<string>> lls = new List<List<string>>();
Button_Click()
{
List<string> str = new List<string>();
for (int i = 0; i < sub.Count; i++)
{
if (checkbx[i].Checked == true)
{
str.Add(checkbx[i].Text);
}
}
lls.Add(str);
}
hence their names would be lls[0], lls[1],... etc
List objects doesn't have names, variables have names.
Creating variables dynamically is mostly useless, especially in compiled languages. What you want is a collection where you can store multiple lists, e.g. a list of lists:
public List<List<string>> str = new List<List<string>>();
public void check() {
List<string> subs = new List<string>();
for (int i = 0; i < sub.Count; i++) {
if (checkbx[i].Checked) {
subs.Add(checkbx[i].Text);
}
}
str.Add(subs);
}
Use a dictionary of lists where the key is the list name and the value is the list itself.
//Defining Dictionary
Dictionary<string, List<string>> ListDict = new Dictionary<string, List<string>>();
//Add lists in Dictionary
OnClick(string listname)
{
ListDict.Add(listname, new List<string>());
}
//Add values in List
ListDict[listname].Add("xyz");

Categories

Resources