Deleting a node from an xmlNodeList - c#

here is my code
public bool limitOutput()
{
double lowerLeftPointX = m_mapControl.CurrentExtent.LowerLeftPoint.X;
double lowerLeftPointY = m_mapControl.CurrentExtent.LowerLeftPoint.Y;
double upperRightPointX = m_mapControl.CurrentExtent.UpperRightPoint.X;
double upperRightPointY = m_mapControl.CurrentExtent.UpperRightPoint.Y;
for(int i = locationElements.Count - 1; i >= 0; i--)
{
if (Double.Parse(locationElements[i]["GEOMETRY_X"].InnerText) < lowerLeftPointX || Double.Parse(locationElements[i]["GEOMETRY_X"].InnerText) > upperRightPointX || Double.Parse(locationElements[i]["GEOMETRY_Y"].InnerText) < lowerLeftPointY || Double.Parse(locationElements[i]["GEOMETRY_Y"].InnerText) > upperRightPointY)
{
locationElements[i].ParentNode.RemoveChild(locationElements[i]);
}
}
if (locationElements.Count == 0)
{
PearMessageBox.Show(PearMessageBox.mBoxType.simpleNotification, "No results found in specified area");
return false;
}
return true;
}
I am trying to delete all the nodes which are not within the boundary I have set. The delete line is executed but does not actually delete as when I count locationElements it is still the same value before the method is executed.
Any ideas what is wrong with the code

The problem is due to the fact that RemoveChild() removed the element from the source XmlDocument, but not from the pre-populated XmlNodeList. So you need to execute again the code that was used to pre-populate locationElements variable, something like this :
//assume that GetLocationElements() is a method...
//...containing the same logic you used to populate locationElements variable
var updatedLocationElements = GetLocationElements();
if (updatedLocationElements.Count == 0)
{
PearMessageBox.Show(PearMessageBox.mBoxType.simpleNotification, "No results found in specified area");
return false;
}
return true;

Related

Inserting into sorted linked list?

I'm very new to coding and I couldn't understand the error in my code, I'd be very grateful for any help.
So the code works fine except for the last element because the element after that is null and I couldn't handle it (I'm very new).
The problem is with the last part.
public static void InsertingIntoSortedLinkedList(int value, int key)
{
Node m = new Node();
m.value=value;
m.key=key;
if (root==null)
{
m.Next = null;
root = m;
}
else
{
if (key<root.key)
{
m.Next = root;
root = m;
}
else
{
Node temp1 = root;
Node temp2 = null;
while ((temp1!=null)&&(temp1.key<key))
{
temp2 = temp1;
temp1 = temp1.Next;
}
if (temp1==null)
{
m.Next = null;
temp2.Next=m;
}
else
{
m.Next = temp1;
if (temp2!=null)//I either put this here and the last element is lost or I got a NullReferenceException. What should I change?
{
temp2.Next = m;
}
}
}
}
}
Thank you for your help.
One situation where you may find a problem is when you insert a value equal to the root value - those values will be skipped because you are trying to insert BEFORE the matching item and not updating the root reference.
The solution is to either insert after the matching value - this can be done by changing the line
while ((temp1!=null)&&(temp1.key<key))
to
while ((temp1 != null) && (temp1.key <= key))
OR by inserting at the root element by changing the line
if (key<root.key)
to
if (key <= root.key)
OR by updating the root value when inserting before
if (temp2!=null)
{
temp2.Next = m;
}
else
root = m;
Any one of the changes should fix the problem
You have two typos:
if (key<root.key)
while ((temp1!=null)&&(temp1.key<key))
missing > at the end of <key

Counting in lists with conditional statements

I know this is a common topic but I have been through most of the threads here on Stackoverflow and having followed them, can't see to get mine to satisfy all conditions.
I want to return the 2nd item in a list and if the list is null or only has 1 item in it, return 0;
I have this:
public int practice(List<int> items)
{
if (items == null)
{
return 0;
}
else if (items.Count == 1)
{
return 0;
}
else
{
int second_place = items[1];
return second_place;
}
}
I can't get this to work if the list has only 1 item in it. It just bypasses my else if condition and then fails.
I have tried items.Count and items.Count() but it doesn't seem to make a difference.
Instead of adding another else condition, you could just combine them as follows:
public int practice(List<int> items)
{
if (items == null || items.Count <= 1)
{
return 0;
}
else
{
int second_place = items[1];
return second_place;
}
}
Ok so I figured out what I wasn't doing correct. The code wasn't passing if the list had 0 items in it (but was not null).
So I added another else if statement to handle that:
else if (items.Count == 0)
{
return 0;
}
And then it passed. I didn't originally do this because I had not initially thought of the case where the list is not null but has 0 items in it. I was incorrectly thinking it had either a value of null or 1 item or greater.

Iterating Through TextBoxes to Check If Empty WPF

I'm attempting to iterate through all the textboxes in my WPF window to see if they are empty, and if they are, the method should set a bool to true.
private void checkTextBoxes(DependencyObject obj)
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
{
if (obj is TextBox && ((TextBox)obj).Text == null)
{
isTextBoxEmpty = true;
}
}
}
isTextBoxEmpty is my bool that has been defined outside of the method. I call the method using:
checkTextBoxes(this);
But the bool always returns false no matter what I do, even if all the text boxes are empty.
Try to change this :
((TextBox)obj).Text == null)
To this :
(String.IsNullOrEmpty((TextBox)obj).Text))
The result you got possibly because TextBox's Text is never null, it is empty string ("") by default, thats what I think, just possibly.
Outside of any syntax errors this should give you the result you expect; This only returns true if ALL textboxes are blank
private void checkTextBoxes(DependencyObject obj)
{
var trueforall = true;
var atleastone = false;
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
{
if (obj is TextBox)
{
if(!atleastone){ atleastone = true;}
trueforall &= string.IsNullOrWhiteSpace(((TextBox)obj).Text);
if (!trueforall) { break; }
}
}
isTextBoxEmpty = trueforall && atleastone;
}

dropdownlist items find by partial value

To find an item (and select it) in a dropdownlist using a value we simply do
dropdownlist1.Items.FindByValue("myValue").Selected = true;
How can I find an item using partial value? Say I have 3 elements and they have values "myValue one", "myvalue two", "myValue three" respectively. I want to do something like
dropdownlist1.Items.FindByValue("three").Selected = true;
and have it select the last item.
You can iterate from the end of the list and check if value contains the item (this will select the last item which contains value "myValueSearched").
for (int i = DropDownList1.Items.Count - 1; i >= 0 ; i--)
{
if (DropDownList1.Items[i].Value.Contains("myValueSearched"))
{
DropDownList1.Items[i].Selected = true;
break;
}
}
Or you can use linq as always:
DropDownList1.Items.Cast<ListItem>()
.Where(x => x.Value.Contains("three"))
.LastOrDefault().Selected = true;
You can iterate the items in your list, and when you find the first one whose items's string contains the pattern, you can set its Selected property to true.
bool found = false;
int i = 0;
while (!found && i<dropdownlist1.Items.Count)
{
if (dropdownlist1.Items.ToString().Contains("three"))
found = true;
else
i++;
}
if(found)
dropdownlist1.Items[i].Selected = true;
Or you could write a method (or extension method) that does this for you
public bool SelectByPartOfTheValue(typeOfTheItem[] items, string part)
{
bool found = false;
bool retVal = false;
int i = 0;
while (!found && i<dropdownlist1.Items.Count)
{
if (items.ToString().Contains("three"))
found = true;
else
i++;
}
if(found)
{
items[i].Selected = true;
retVal = true;
}
return retVal;
}
and call it like this
if(SelectByPartOfTheValue(dropdownlist1.Items, "three")
MessageBox.Show("Succesfully selected");
else
MessageBox.Show("There is no item that contains three");
Above mentioned answers are perfect, just there are not case sensitivity proof :
DDL.SelectedValue = DDL.Items.Cast<ListItem>().FirstOrDefault(x => x.Text.ToLower().Contains(matchingItem)).Text

Sorting a DropDownList?

I'm curious as to the best route (more looking towards simplicity, not speed or efficiency) to sort a DropDownList in C#/ASP.NET - I've looked at a few recommendations but they aren't clicking well with me. this drop down is giving me list in alphabetical order. But I have to sort out randomly.
Note:I do not have control over how the data comes into the DropDownList - I cannot modify the SQL.
public void populateLocationList()
{
DataTable dt_locations = (DataTable)daa_addresses.GetDataByEventLocations(int_eventid);
if (dt_locations != null && dt_locations.Rows.Count > 0)
{
// Populate locations dropdown menu
// Bind locationsList instead of dt_locations
ddl_locations.DataTextField = "Key";
ddl_locations.DataValueField = "Value";
ddl_locations.DataSource = RemoveDuplicateLocations(dt_locations);
ddl_locations.DataBind();
string location = "";
// Set the selection based upon the query string
if (Request.QueryString["loc"] != null)
{
location = Request.QueryString["loc"];
locationLbl.Text = Request.QueryString["loc"];
locationID.Value = "-1";
}
if (dt_locations.Rows.Count == 1)
{
location = ddl_locations.Items[0].Text;
locationLbl.Text = location;
}
// Set location in drop down list
int int_foundlocation = 0;
bool foundLocation = false;
foreach (ListItem lsi_item in ddl_locations.Items)
{
if (lsi_item.Text.ToLower().Trim() == location.ToLower().Trim())
{
int_foundlocation = ddl_locations.Items.IndexOf(lsi_item);
foundLocation = true;
break;
}
}
ddl_locations.SelectedIndex = int_foundlocation;
if (ddl_locations.Items.Count == 1)
{
// Make location label visible.
locationLbl.Visible = true;
ddl_locations.Visible = false;
}
else
{
locationLbl.Visible = false;
ddl_locations.Visible = true;
}
//* defualt location S for short courses *//
if (!IsPostBack && !foundLocation)
{
ListItem s = ddl_locations.Items.FindByText("S");
int index = 0;
if (s != null)
{
index = ddl_locations.Items.IndexOf(s);
}
ddl_locations.SelectedIndex = index;
ddl_locations.DataBind();
}
}
}
I have to sort out randomly.
You'd have to shuffle rows, probably with something close to this code (borrowed from #configurator's answer):
internal static class Extensions
{
internal static IEnumerable<T> Shuffle<T>(this IEnumerable<T> source, Random rng)
{
T[] elements = source.ToArray();
// Note i > 0 to avoid final pointless iteration
for (int i = elements.Length - 1; i > 0; i--)
{
// Swap element "i" with a random earlier element it (or itself)
int swapIndex = rng.Next(i + 1);
yield return elements[swapIndex];
elements[swapIndex] = elements[i];
// we don't actually perform the swap, we can forget about the
// swapped element because we already returned it.
}
// there is one item remaining that was not returned - we return it now
yield return elements[0];
}
}
Assuming that RemoveDuplicateLocations returns a DataTable the binding part of your code should be changed to:
ddl_locations.DataSource = RemoveDuplicateLocations(dt_locations)
.AsEnumerable()
.Shuffle(new Random())
.CopyToDataTable();

Categories