views:

98

answers:

2

Hi

I had to change on my lines of code around. I before had something like this

// this is in a static method.
List<string> mySTring = new List<string>();

mySTring.add("one");
mySTring.add("two");

However on one of my pages I have a dropdownlist that does not require the field "two" so instead of writing duplicate code all I did was

myString.remove("two");

Now I need to change my list to a List<SelectListItem> myList = new List<SelectListItem>();

So I have it now looking like this:

  List<SelectListItem> myList = new List<SelectListItem>()
            { 
                new SelectListItem() { Text = "one", Value = "one"},
                new SelectListItem() { Text = "two", Value = "two"},
            };

So now how do I remove the selectListItem that contains "two"? I know I probably could use remove by index. But I might add to list in the future so I don't want to start hunting down and changing it if the index changes.

Thanks

A: 

List<T> is, by default, going to be comparing object references (unless SelectListItem implements a custom equality method). So unless you still have a reference to the second item around, you are going to have to get it either by reference, or by finding the desired item:

var item = myList.First(x=>x.Value == "two");
myList.Remove(item);

Index may be easier...

Marc Gravell
hmm was hoping to now have to search for it. I won't have the reference anymore, I guess I will make remove by index or by finding. Not sure what to use. Just concerned in the future I add something to my list collection and all of a sudden it is a different index and I am trying to figure out why it is not wokring and that is the reason.
chobo2
Also how would the List collection sort method work on this? Because I was using the sort method on my list of strings(thats why I am concerned the index will change).
chobo2
Well, you could always use a different container that doesn't require searching by brute force.
spender
`List<T>`'s sorting works on standard sorting; it depends whether `SelectListItem` implements `IComparable` or `IComparable<SelectListItem>`.
Marc Gravell
my list does not give me an option for "First" does certain list object not get it?
chobo2
Hmm the sort method does not work either. So any ideas on how to sort it?
chobo2
The First method shown is LINQ, which should be available since you are using MVC. Try adding "`using System.Linq;`" to the top of that file. Sort is tricky since there is no inbuilt method that will work on the **words**.
Marc Gravell
+2  A: 

You could use the RemovalAll method:

myList.RemoveAll(i => i.Text == "two");

Obviously this will get rid of all the items whose "Text" property is "two", but since you're using it in a ComboBox I'm assuming you'll only have one item for each "Text" value.

Matt Hamilton