0
var courses = _repository.GetAllCoursesDetailsByCourseId(id);
var result = (from s in courses select new {  id = s.Course_ID,  name=s.Course_Date}).Distinct().ToList();

Now what i want to do is to iterate through result and edit all of its "name" content . . a rough idea is below :

foreach (var i in result)
{
     string[] temp = i.name.Split(',');
     string[] token = temp[0].Split(' ');
     string newtemp = token[1] + " " + temp[1];
     i.name = newtemp;
}

But this is not working. How can i edit the content in var result?

Igor Ševo
  • 5,459
  • 3
  • 35
  • 80
ZaraQ
  • 57
  • 1
  • 12

6 Answers6

0
Try something like this:

foreach (var i in result)
{
 string temp = i.name.Split(',');
 string token = temp.Split(' ');
 string newtemp = token + " " + temp;
 i.name = newtemp;
 }
Ni3
  • 489
  • 3
  • 12
0

Anonymous objects are immutable, that's why you're getting the Readonly error message.

I suggest you look here for some more information: Why are the properties of anonymous types in C# read-only?

Community
  • 1
  • 1
Omri Aharon
  • 16,959
  • 5
  • 40
  • 58
0

Anonymous type properties are readonly.

Build a function that does the name generation and then use it directly in the LINQ:

private string GenerateNewName(string name) {
    string temp = name.Split(',');
    string token = temp.Split(' ');
    return token + " " + temp;
}

var result = (from s in courses select new {  id = s.Course_ID,  name=GenerateNewName(s.Course_Date)}).Distinct().ToList();
Denat Hoxha
  • 915
  • 8
  • 16
0

This should fix your problem. (I didn't change your code, but you should be careful with your index, if you didn't found any ',' or ' ' you will throw an exception)

var result = (from s in courses select new {  id = s.Course_ID,  name= splitName(s.Course_Date) }).Distinct().ToList();

private string splitName(string value)
{
     string[] temp = i.name.Split(',');
     string[] token = temp[0].Split(' ');
     return (token[1] + " " + temp[1]);
}
Gaston Siffert
  • 372
  • 1
  • 8
0

When you use foreach ,whatever changes you do, the changes are in the temp var i, not in the actual list, try using the traditonal for or an iterator.

Adwait
  • 290
  • 2
  • 11
0

As @Muhammad said, you need another list with updated values. You can extend your list search through Where extension method on any list, then apply your changes like below,

var newResult = result.Where(q=> q.name == "ValueToUpdate").ToList().ForEach(i => i.name = "NewValue");
Palak Bhansali
  • 731
  • 4
  • 10