Change state of List<T> inside extension method

233 views Asked by At

How do I change the state of List which is part of view model in extension method so the view model reflects this change without having to re assign the value

Code:

//ViewModel:

//This line should modify the change internally wihtout having to reassign like

// ..Selected =model.CheckBoxList.Selected.RemoveWhere(c => c.SelectedValue == null)

  model.CheckBoxList.Selected.RemoveWhere(c => c.SelectedValue == null) 

Extension Method :

 public static IEnumerable<T> RemoveWhere<T>(this IEnumerable<T> source, Predicate<T> predicate)

{

            var x = source.ToList();
            x.RemoveAt(1);
            source = x;
            return source;

}

Update:

public class CheckBoxList
    {
        public CheckBoxList()
        {
            //Selected = new List<CheckBoxListViewModel>();
        }

        [XmlElement("SelectedItem")]
        public List<CheckBoxListViewModel> Selected { get; set; }
    }

    [XmlRoot(ElementName = "MyClass")]
    public class CheckBoxListViewModel
    {
        public string SelectedValue { get; set; }
        public string SelectedDescription { get; set; }
    }
1

There are 1 answers

1
SLaks On BEST ANSWER

Assign a parameter has no effect on the expression you pass to the method.

You instead want to mutate the existing instance. To do that, you need to accept a mutable type; namely, List<T>.

List<T> already has a RemoveAll() function which does exactly that, so you don't need to do anything at all.