0

I have a collection of objects, that have a property of type IEnumerable<string>

My code

foreach (var student in students)
{
    string term = SomeMethodhere();

    students.Where(x => x.Id == student.Id)
                  .ToList()
                  .ForEach(x => 
                         { 
                            x.FieldsOfStudy.ToList().Add(term); 
                         });
 }

I have no erros, but FieldsOfStudy, remain unchanged.

What am I missing?

1
  • 4
    x.FieldsOfStudy.ToList() creates a new list which you discard then; it should be something like x.FieldsOfStudy.Add(term); Commented Nov 3, 2016 at 9:31

3 Answers 3

3

What am I missing?

ToList() creates a new list with all elements found in FieldOfStudy. It does not modify the original enumeration.

In fact, there is no guarantee anything can modify the original enumeration; it is well possible FieldsOfStudy is actually an array (and thus no elements can be added).

Bottom line: You are not supposed to modify something provided as IEnumerable<T>. If you want FieldsOfStudy to be mutable, declare it typed to an interface that provides methods for modifying the list, such as IList<T> or ICollection<T>.

Design philosophy: If you declare the FieldsOfStudy property as IEnumerable<T>, you indicate that the object returned from that property might be anything that implements IEnumerable<T>. If, in calling code, you rely on casting that object to something more specific (something to which items can be added), that calling code might break when the implementation of the FieldsOfStudy property changes. Things may be a bit different if the FieldsOfStudy property can be assigned to, as calling code can then control what is stored in the property.

Sign up to request clarification or add additional context in comments.

Comments

2

x.FieldsOfStudy.ToList() produces a new instance of list. So you are actually adding element to new collection.

Possible workarounds (if you can set new instace of list to property FieldsOfStudy):

{ 
   var list = x.FieldsOfStudy as IList<string> ?? new List<string>(x.FieldsOfStudy);
   list.Add(term);
   x.FieldsOfStudy = list;
}

Comments

0

Here loop is made for students and then each student is updated in same loop.

Possible solution and changes : Provided Field of study is ICollection or Iist

students.ToList().ForEach(s=>s.FieldsOfStudy.Add(SomeMethodhere()));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.