Add string to array only if data is available - c#

I have some code that builds a string array using data from a form:
string[] var4 = new string[] {
"Issue=" + DropDownListIssue.SelectedItem.ToString(),
"SubIssue=" + DropDownListSubIssue.SelectedItem.ToString(),
"Layout=" + DropDownListLayout.SelectedItem.ToString()
};
This code adds all the elements to the array even if there is no data. For example, say the value of Issue is "Apple," but the other two dropdownlists are left blank. The resulting var4 would be this:
"Issue=Apple"
"SubIssue="
"Layout="
In this case, I would like var4 to be:
"Issue=Apple"
SubIssue and Layout are not added to the array as they are left blank. If they are filled in, however, then they should be added to the array. Example:
"Issue=Apple"
"SubIssue=Dog"
"Layout=Square"
How can I write this to only add the string when it has a value?

You can do the following:
string[] possibleNulllVar4 = new string[] {
string.IsNullOrEmpty(DropDownListIssue.SelectedItem.ToString()) ? "Issue=" + DropDownListIssue.SelectedItem.ToString() : null,
string.IsNullOrEmpty(DropDownListSubIssue.SelectedItem.ToString()) ? "SubIssue=" + DropDownListSubIssue.SelectedItem.ToString() : null,
string.IsNullOrEmpty(DropDownListLayout.SelectedItem.ToString()) ? "Layout=" + DropDownListLayout.SelectedItem.ToString() : null
};
Edit: Ah, if you don't want any empty nodes, do the following afterward:
var var4 = possibleNulllVar4.Where(x => null != x).ToArray();
Easy!

List<string> list = new List<string>();
var str = DropDownListIssue.SelectedItem.ToString();
if (!string.IsNullOrEmpty(str))
list.Add("Issue=" + str);
str = DropDownListSubIssue.SelectedItem.ToString();
if (!string.IsNullOrEmpty(str))
list.Add("SubIssue=" + str);
str = DropDownListLayout.SelectedItem.ToString();
if (!string.IsNullOrEmpty(str))
list.Add("Layout=" + str);
string[] var4 = list.ToArray();

I'm on a phone so please forgive some of the grammar / spelling / code sample if it doesn't work as is...
But the generic idea is this:
Why not loop through a collection of those DropDown lists, if one has a selected value, add the value to the passed in array (or use an Arraylist.ToArray() or List.ToArray()) so yo udon't need to redim it. Each dropdown can have a argument/command on it, so you'd know which one you're dealing with:
Similar to (PSEUDO)
List<DropDowns> dropDowns = ...//Get your dropdowns into the list
foreach(dd in dropDowns)
{
if(dd.SelectedItem != null && d.SelectedIndex != -1 )
YourStringArray.Add(dd.CommandArgument + "=" + dd.SelectedValue);
}
Sorry - on phone so it might not "compile" but that's why I marked id pseduo. Doing a List<> and a Foreach isn't the most efficient, but it gets away from ugly massive if statements.

Related

Splitting combined string for checklistbox control

RE: Customised Web Application for Microsoft CRM Online
I've programmed a checklistbox control in ASP.NET (C#) Web Form that displays a number of items from Microsoft CRM Online via LINQ.
List<string> selDropdown = chkMyItemsHere.Items.Cast<ListItem>()
.Where(li => li.Selected)
.Select(li => li.Value)
.ToList();
string ListBoxValues = string.Join(", ", selDropdown);
This works perfectly and I'm able to save the string into one field (i.e. 'string value, string value').
Now, on Page_Load I need to split the values from the combined string and tick the relevant checkboxes in the checkListbox.
string[] k = i.LINQFIELD.Split(',');
for (int m = 0; m <= k.Length - 1; m++)
{
for (int x = 0; x <= chkMyItemsHere.Items.Count; x++)
{
if (chkMyItemsHere.Items[x].Value == k[m])
{
chkMyItemsHere.Items[x].Selected = true;
}
}
}
Any ideas why this wouldn't be re-populating my checkboxlist? Any help would be greatly appreciated.
In your code that works, you have this:
string.Join(", ", selDropdown);
In your code that does not, you have this:
string[] k = i.LINQFIELD.Split(',');
Do you see it?
As a solution, I propose you declare a constant variable like so:
private const string SPLIT_VARIABLE = ", ";
Now you have this:
string.Join(SPLIT_VARIABLE, selDropdown);
and
string[] k = i.LINQFIELD.Split(SPLIT_VARIABLE);
After fixing how you split your comma-delimited string -- as suggested by jp2code to make sure there aren't extraneous spaces in each array element -- you can also use LINQ to select the items in your checkboxlist based on what's in your "k" string array:
(from i in chkMyItemsHere.Items.Cast<ListItem>()
where Array.Exists<string>(k, s => { return i.Value == s; })
select i).ToList().ForEach(i => i.Selected = true);
This way, you don't have to use a nested for loop to select your list items.

quick and simple way to sort this data taken from a tsv and make it distinct as per one of the fields that it contains

I want to know the quickest and simplest way to sort the code shown below. Sorting from newRecord.AppCode would not be suitable as it will change the meaning of the output. So I need to sort every line from string outp. What would be the best way? Also I would like to make every row distinct. I beleive using LINQ would be very quick but I am not that great at it. Help appreciated. So close to getting it done! Note: Data is being pulled from a tsv. Using .net 3.5, visual studio 2008) Will mark answer as soon as I get progress. :)
while ((line = sr.ReadLine()) != null)
{
String[] splitted = line.Split('\t');
appcodes.Add(line);
Records newRecord = new Records();
newRecord.Server = splitted[0];
newRecord.Instance = splitted[1];
newRecord.AppCode = splitted[2];
newRecord.Database = splitted[3];
listrecords.Add(newRecord);
for (int i = 0; i < appcodes.Count(); i++)
{
if (newRecord.AppCode==appcodes[i].ToUpper())
{
String outp = newRecord.AppCode + " " + newRecord.Server + " " + newRecord.Instance + " " + newRecord.Database;
Console.WriteLine(outp);
}
}
}
have lists named Keepers and newkeepers. Was trying to do something like outp.sort() and outp.sort() but it doesnt work in strings. This is how I solved the problem.
Keepers.Add(outp);
Keepers.Sort();
newKeepers = Keepers.Distinct().ToList();
foreach (object o in newKeepers)
{
Console.WriteLine(o);
}
Console.ReadLine();
As you can see, newrecords contain different fields so I wrote a LINQ statement to solve the problem.
var sorted_list = (from r in newrecords
orderby r.AppCode, r.Server, r.Instance, r.Database
select r).Distinct().ToList();
var distinctSortedList = sorted_list.Distinct().ToList();

Procedurally create a dynamic object for Dapper

I've seen many posts about creating ExpandoObject objects and such, but it does not work in my case. I need to create an object like
var someObj = new {
term1 = "someValue",
term2 = "other",
...
};
Basically, we are using Dapper and we need to create a query dynamically, where the WHERE clause is fabricated from a given array of arguments. We are not generalizing queries! It's a single method receiving a variable number of arguments and we need to check OR each value on a single column.
Right now, the only viable solution is to revert and directly use System.Data.SqlClient.SqlConnection, or is there any way to make this work?
Update:
This is what most likely should work, but doesn't :
string inWhere = null;
dynamic inTerms = new ExpandoObject();
IDictionary<string, object> inTermsDict = inTerms;
if (!(string.IsNullOrEmpty(filter.Term) || string.IsNullOrWhiteSpace(filter.Term))) {
inWhere = "(" + string.Join(" OR ", filter.Terms.Select((t, i) => "{0} LIKE #p" + i)) + ")";
int termIndex = 0;
foreach (string term in filter.Terms) {
inTermsDict.Add("p" + (termIndex++), term);
}
}
// ...
var rows = db.Query("SELECT * FROM {table} WHERE {baseCondition}" +
(string.IsNullOrEmpty(inWhere) ? "" : string.Format(" AND " + inWhere, "columnName")),
inTerms as object);
Just to answer my own question, as we found the proper solution earlier today.
Simply put, we found the IDynamicParameters And this class simply solves everything, acting as a Dictionary.
var inTerms = new Dapper.DynamicParameters();
inTerms.Add("#p" + (termIndex++), somveValue);
Everyone's happy!

How can I set the right parameters of dataset.Table[0].Compute(string expression,string filter)?

I can not get the right result from the following code block:
object ob = ds_bug.Tables[0].Compute("Count(id)",str_vertical +"= '"+"' and "+str_horizontal+" = '"+first_row.Cells[j].Text.ToString()+"'");// ds_bug has been filled some data.
str_vertical and str_horizontal are two fields from the ds_bug.Tables[0], and I can see their values are right too when I debug the code.
Is there any problem I set the filter with a string like " a = '##' and b = '##' " ?
First you should split the method call and the initialization of the expression and the filter, that makes it clearer:
I assume that first_row.Cells[j].Text.ToString() is a static value that you've queried previously, so you can declare it like:
String firstRowCellsJText = first_row.Cells[j].Text.ToString();
String expression="Count(id)";
String filter = "str_vertical=str_horizontal + " + firstRowCellsJText;
object ob = s_bug.Tables[0].Compute(expression,filter);

replacing variable in elements of a List

A more simple example might be:
List <myElement> Elements;
Elements.Add(my1);
Elements.Add(my2);
my1 and my2 eache have a variable of type string named myString
Now I want to change the value of my1.myString. But if I change it the value my2.myString gets changed aswell.
Hopefully it's a bit clearer now
I'm using a List with several Elements within it in C#. The List has as type a self-defined class with several variables in it.
Now I want to change in one list-element the value of a variable. But unfortunately the value gets replaced not only on this but in all elements of this list.
Any advice on how to fix this?
MyProjectElement File1 = this.Project.Elements[0];
MyProjectElement File2 = this.Project.Elements[1];
MyProject my1 = (MyProject)File1;
MyProject my2 = (MyProject)File2;
PageCount_F1 = my1.PageCount;
PageCount_F2 = my2.PageCount;
if (PageCount_F1 != PageCount_F2)
MessageBox.Show("The 2 files need to have the same file length", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
else
{
my1.IncludeAllPages = false;
my2.IncludeAllPages = false;
for(int i=1; i <= PageCount_F1; i++)
{
StringBuilder value1 = new StringBuilder();
StringBuilder value2 = new StringBuilder();
value1.Append("" + i);
value2.Append("" + (PageCount_F2-i+1));
MyProject my1new = new MyProject();
MyProject my2new = new MyProject();
my1new.Pages = value1.ToString();
my2new.Pages = value2.ToString();
my1.Pages = my1new.Pages;
my2.Pages = my2new.Pages;
this.Project.Elements.Add((myProjectElement)my1);
this.Project.Elements.Add((myProjectElement)my2);
((MyProject)this.Project.Elements[1]).Pages.Remove(0);
((MyProject)this.Project.Elements[i]).Pages.Remove(0);
((MyProject)this.Project.Elements[1]).Pages = "" + 1;
((MyProject)this.Project.Elements[PageCount_F2 - i + 1]).Pages = "" + (PageCount_F2 - i + 1);
((MyProject)this.Project.Elements[i-1]).Pages.Remove(0);
((MyProject)this.Project.Elements[i]).Pages.Remove(0);
((MyProject)this.Project.Elements[i - 1]).Pages = "" + i;
((MyProject)this.Project.Elements[i]).Pages = "" + (PageCount_F2 - i + 1);
}
You need to specify what the condition is to make a change. For example:
myList.ForEach(x => if(whateverCondition) x.myString = "blah" );
But you really need to ascertain what that condition is.
The problem is that in the code that you've put up you're changing your values in a loop that steps through every element and the loop starts indexing the List with index 1, whereas the first element in index 0.
If you're only after changing one element then select that element. Moo-Juice has posted a good suggestion (+1 btw).
p.s. don't post links to external stores with your code, many users that sit behind corporate firewalls can't access them.

Categories

Resources