This is my first question here, so sorry for any wrong information or about my English.
I need to convert a List<Object> to List<Hashtable>
string IdsLista = string.Empty;
foreach (DataRow rows in ListaItensTransferencia.Rows)
{
IdsLista += Convert.ToString(rows["Id Bem"]) + ",";
}
string[] idsSelecionadosListaTransferencia = IdsLista.Split(',');
List<object> listaIdsSelecionadosListTransferencia = new List<object>(idsSelecionadosListaTransferencia.Length);
listaIdsSelecionadosListTransferencia.AddRange(idsSelecionadosListaTransferencia);
wuc_itensTransferencia.checkBoxGrid = listaIdsSelecionadosListTransferencia;
//v this is the list<hashtable> v this is the list<object>
wuc_itensTransferencia.ItensSelecionados = listaIdsSelecionadosListTransferencia;
How do I do this ?
Instead of putting data into list of object, put directly into list of hashtable. Why you want to create the comma separated string. Try this
List<HashTable> hashTable = new List<HashTable>();
foreach (DataRow rows in ListaItensTransferencia.Rows)
{
hashTable.Add(new HashTable("Id Bem", Convert.ToString(rows["Id Bem"])));
}
Related
I am junior developer and I am trying to populate an ArrayList from a Dictionary. My problem is rather then adding a new record to the ArrayList it adds the new record but also overwrites the values for all the other values in the array.
So if I inspect the values as the ArrayList is being populated I see the values from the Dictionary as expected. But when that row is inserted into the ArrayList all of the existing rows are over written with the data from current Dictionary Row. So I end up with an ArrayList with several rows that are a duplicate of the last record added from the dictionary. My code is shown below. Can someone please tell me what am I doing wrong? Code below
ArrayList arrData = new ArrayList();
eSummary edata = new eSummary();
//Starts with the first 50 recods retrieved and adds them to the ArrayList. Loops thru to get remaining records
while (blnEmpty)
{
if (response.IsSuccessStatusCode)
{
string json = response.Content.ReadAsStringAsync().Result;
var jss = new JavaScriptSerializer();
var dict = jss.Deserialize<Dictionary<string, dynamic>>(json);
for (int i = 0; i < dict.Values.Sum(x => x.Count); i++)
{
foreach (var item in dict)
{
string checkId = (dict["data"][i]["Id"]);
edata.Id = dict["data"][i]["Id"];
edata.idExternal = (dict["data"][i]["idExternal"]) == null ? "" : (dict["data"][i]["idExternal"]);
edata.Type = "Video";
edata.ownerId = (dict["data"][i]["uploadedByOwnerId"]);
edata.dateUploaded = Convert.ToDateTime((dict["data"][i]["dateUploaded"]));
edata.durationSeconds = Convert.ToDouble((dict["data"][i]["durationSeconds"]));
edata.category = (dict["data"][i]["categories"]).Count < 1 ? string.Empty : (dict["data"][i]["categories"][0]);
edata.title = (dict["data"][i]["title"]) == string.Empty ? string.Empty : (dict["data"][i]["title"]);
edata.dateRecordStarted = Convert.ToDateTime((dict["data"][i]["dateRecordStart"]));
edata.DateAPIRan = DateTime.Now;
if (CheckAutoTag(checkId, dict["data"][i]["tags"]))
{
edata.AutoTagged = true;
}
else edata.AutoTagged = false;
arrData.Add(edata);
edata is a reference type. You keep updating the values of a single object within the loop.
You need to call new eSummary() and set the values on the new object and then add that to your list.
But do note, you should not be using ArrayList in modern c#. Use a List<eSummary> instead.
I am trying to customise a DevExpress grid filter.
Currently I return the data from my api, and so I need to parse the built in string which is returned from the grid.
An example of the filter string is;
StartsWith([name], 'test') And StartsWith([quantity], '12') And
StartsWith([id], '1') And StartsWith([date], '01/10/2015')
I would like to convert this to a Dictionary in the most efficient way?
You could use Regex for filtering the key/value pair outta your string and a simple foreach to prepare the dictionary.
This could be a solution:
public static Dictionary<string, object> FilterAPIData(string data)
{
var r = new Regex(#"\[\w+\], \'[\w/]+\'");
var result = r.Matches(data);
var dict = new Dictionary<string, object>();
foreach (Match item in result)
{
var val = item.Value.Split(',');
dict.Add(val[0], val[1]);
}
return dict;
}
Regex might be the best option for this, but I'll show you how to do it without Regex as it can be a bit difficult to understand.
Assuming your string will always be in this format you can do this:
string str = "StartsWith([name], 'test') And StartsWith([quantity], '12') And StartsWith([id], '1') And StartsWith([date], '01/10/2015')";
var strArray = str.Split(new string[]{"And "}, StringSplitOptions.None);
var dict = new Dictionary<string, string>();
foreach(var value in strArray)
{
dict.Add(GetStringBetween(value, "[", "]"), GetStringBetween(value, "'", "'"));
}
private string GetStringBetween(string value, string startDelim, string endDelim)
{
int first = value.IndexOf(startDelim) + startDelim.Length;
int last = value.LastIndexOf(endDelim);
return value.Substring(first, last - first);
}
//Output :
//name test
//quantity 12
//id 1
// date 01/10/2015
If there other formats the string can be in you can adjust as needed. I would also consider adding in more validation/error handling, but I will let you figure that out ;)
Below is my C# code to populate the multi-selected items from the listbox
List<string> listCountry = new List<string>();
for (int i = 0; i < lstCountry.Items.Count; i++)
{
if (lstCountry.Items[i]Selected)
{
countries = listCountry.Add(lstCountry.Items[i].ToString());
}
}
And I have a line to call the method to run the report with the above parameters:
retVal = CR.GetReport(Company, countries);
My question is : What data type should I define for countries since it keeps giving me error like "can't implicitly convert type 'void' to 'string'" when I define countries as
string countries = null;
What did I do wrong here? Please help, thank you very much
Sorry I didn't make it clear enough, I have another the function GetReport() which is defined as
public CrystalDecisions.CrystalReports.Engine.ReportDocument GetReport( string Company, string countries)
{
CrystalDecisions.CrystalReports.Engine.ReportDocument retVal = new rptReortData();
ReportLogon rptLog = new ReportLogon();
rptLog.logon(retVal, "Report");
retVal.SetParameterValue("P_Country", new string[] { country});
}
How do I get the value from the listbox assign to countries
You didn't provide the name of your function but I guess it's GetReport. It doesn't return any value so you can't assign the retVal. Try the below:
CR.GetReport(Company, countries);
I'm a little puzzled by your question, but I'm guessing that the CR.GetReport function is raising an exception? So your data-type for countries depends on that function.
I might make the following change:
listCountry.Add((lstCountry.Items[i] == null ? string.Empty : lstCountry.Items[i].ToString()));
List<string> listText = new List<string>();
List<string> listValue = new List<string>();
foreach (int index in ListBox1.GetSelectedIndices()) {
listText.Add(ListBox1.Items[index].Text);
listValue.Add(ListBox1.Items[index].Value);
}
You need to return retVal from your function
public CrystalDecisions.CrystalReports.Engine.ReportDocument GetReport( string Company, string countries)
{
CrystalDecisions.CrystalReports.Engine.ReportDocument retVal = new rptResearchDataDownload();
ReportLogon rptLog = new ReportLogon();
rptLog.logon(retVal, "Report");
retVal.SetParameterValue("P_Country", new string[] { country});
// ADD THIS LINE
return retVal;
}
Also you need convert the list to a string. You can do this like this:
countries = listCountry.Aggregate((list, c) => list + c + ",");
I have a foreach loop going that is adding e-mail address to an array. At the end I join the array and push it into a string.
I have an issue when someone in the database has a blank email address it messes up my logic. Can someone help me fix this?
TestGuy1:
TestGuy2: 2#2.com
TestGuy3: 3#3.com
With the above information it creates a 3 length array and then turns it into a string like so:
sEmailList "2#2.com,3#3.com," string
Code:
DataTable GetUserReportsToChain = objEmployee.GetUserReportsToChain(LoginID, ConfigurationManager.AppSettings.Get("Connection").ToString());
int RowCount = GetUserReportsToChain.Rows.Count;
string[] aEmailList = new string[RowCount];
int iCounter = 0;
foreach (DataRow rRow in GetUserReportsToChain.Rows)
{
if (rRow["usrEmailAddress"].ToString() != "")
{
aEmailList[iCounter] = rRow["usrEmailAddress"].ToString();
iCounter++;
//String email = rRow["usrEmailAddress"].ToString();
}
}
string sEmailList = String.Join(",", aEmailList);
Any idea how I can fix this when the database has a blank value for e-mail?
All in one
var sEmailList = String.Join(",",
GetUserReportsToChain.Rows
.Cast<DataRow>()
.Select(m => m["usrEmailAddress"].ToString())
.Where(x => !string.IsNullOrWhiteSpace(x)));
You want to use List<string> instead of fixed size array. Or simple LINQ query that returns non-empty strings.
List<string> aEmailList = new List<string>();
foreach (DataRow rRow in GetUserReportsToChain.Rows)
{
if (!String.IsNullOrEmpty(rRow["usrEmailAddress"].ToString()))
{
aEmailList.Add(rRow["usrEmailAddress"].ToString());
}
}
string sEmailList = String.Join(",", aEmailList);
you can try with
String.Join(",", aEmailList.Where(s => !string.IsNullOrEmpty(s)));
You can change your if statement to:
if(!string.IsNullOrEmpty(rRow["usrEmailAddress"].ToString().Trim())
If you're using 3.0 or higher:
String.Join(",", aEmailList.Where(s => s.Trim() != ""));
I am having a dictionary of string as key and List as value.
And adding the entry in the following manner:-
allDDLs = new Dictionary<string, List<string>>();
List<string> temp;
temp = ddlData.get("INV_DDL_Access_Mechanism", "Type");
allDDLs.Add("Access_Mechanism", temp);
temp = ddlData.get("INV_DDL_Application_Operating_System", "OS_Name");
Like this, there are 18 entries. But when I debugged the code, I found that all the values are same as that of the last entered value. But the keys are fine.
For example, when I get the value for "INV_DDL_Access_Mechanism", I get the value same as that of for "INV_DDL_Application_Operating_System".
I don't know what is wrong with it. Any help would be appreciated. :-)
Thanks in advance!
EDIT 1:
Code for accessing the Dictionary values:
List<string> listOfColumns = allDDLs.Keys.ToList<string>();
for(int i = 0; i < listOfColumns.Count(); ++i) {
string columnName = listOfColumns[i].ToString();
List<string> tempDDL = new List<string>();
tempDDL = allDDLs[columnName];
List<string> columnValues = DataColumnToList(columnName, excelDataSet.Tables[0]);
for (int j = 0; j < columnValues.Count(); ++j ) {
if (!tempDDL.Contains(columnValues[j])) {
errorReport.Rows[j][columnName.ToString()] = columnValues[j].ToString() + "LOLOLOL";
}
}
}
Edit 2:
Code of "get" method.
public List<string> get(string tableName, string parameter) {
ds.Clear();
valuesForDDL.Clear();
ds = objDatabase.ByText("Select distinct " + parameter + " from " + tableName + " where Del_Status = 'Available'");
foreach (DataRow row in ds.Tables[0].Rows) {
valuesForDDL.Add(row.ItemArray[0].ToString());
}
return valuesForDDL;
}
You said in your comment:
I clear the list in that code before adding new items to it. And then return the list.
This could be the problem, ... if you return the same List<string> in every call of ddlData.get() (using an instance/static field or property) and you just do a List<string>.Clear() you overwrite the content of the last returned list.
In your ddlData.get() you should do a new List<string>() instead of Clear()ing an existing list.
If that isn't your problem, please post more code (especially the ddlData.get() method, or the whole class).
Issue is with your get method.
On every call to get you return valuesForDDL, and then on next call you clear it and repopulate it. See the bug yet?
valuesForDDL must NOT be a field. This is akin to having a global state, and global state kills. Make it local and your code will work.
public List<string> get(string tableName, string parameter) {
var valuesForDDL = new List<Whatever>();
var ds = objDatabase.ByText("Select distinct " + parameter + " from " + tableName + " where Del_Status = 'Available'");
foreach (DataRow row in ds.Tables[0].Rows) {
valuesForDDL.Add(row.ItemArray[0].ToString());
}
return valuesForDDL;
}
EDIT:
Orthogonal note: With LINQ, you can make this code look much more nicer. I'll refactor your code as follows:
public IEnumerable<string> Get(string tableName, string parameter) {
var ds = objDatabase.ByText("Select distinct " + parameter +
" from " + tableName + " where Del_Status = 'Available'");
return ds.Tables[0].Rows.Select(row => row.ItemArray[0].ToString());
}
You are using the same instance of List ("temp" in your code).
Instantiate a new
List<string>
for each dllData.get(".... and it'll be just fine.
List<string> temp1 = ddlData.get("INV_DDL_Access_Mechanism", "Type");
List<string> temp2 = ddlData.get("INV_DDL_Application_Operating_System", "OS_Name");
....
allDDLs.Add("Access_Mechanism", temp1);
allDDLs.Add("Application_Operating_System", temp2);
EDIT
You would prefer not using temp variables, so use:
allDDLs.Add("Access_Mechanism", ddlData.get("INV_DDL_Access_Mechanism", "Type"));
allDDLs.Add("Application_Operating_System", ddlData.get("INV_DDL_Application_Operating_System", "OS_Name"));
If ddlData.get(...) creates a new List<string> each time, it'll work for sure.