如何在扩展方法中更改作为视图模型一部分的List的状态,以便视图模型反映此更改而无需重新赋值
代码:
//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)
扩展方法:
public static IEnumerable<T> RemoveWhere<T>(this IEnumerable<T> source, Predicate<T> predicate)
{
var x = source.ToList();
x.RemoveAt(1);
source = x;
return source;
}
更新
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; }
}
答案 0 :(得分:2)
分配参数对传递给方法的表达式没有影响。
您反而希望改变现有实例。要做到这一点,你需要接受一个可变类型;即total_bugs = 0 #assuming you can't get half bugs, so we don't need a float
for day in xrange(1, 8): #you don't need to declare day outside of the loop, it's declarable in the for loop itself, though can't be refernced outside the loop.
bugs_today = int(raw_input("How many bugs did you collect on day %d" % day)) #two things here, stick to raw_input for security reasons, and also read up on string formatting, which is what I think answers your question. that's the whole %d nonsense.
total_bugs += bugs_today #this is shorthand notation for total_bugs = total_bugs + bugs_today.
print total_bugs
。
List<T>
已经有一个List<T>
函数就是这样,所以你根本不需要做任何事情。