SGN SGN - 1 month ago 7
C# Question

Adding string to IEnumerable of type string using LINQ to entities

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?

Answer

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;
}