Reputation: 46222
I have the following in linq:
var rss = result.Select(x => new { x.SampleDate, x.DataValue })
.OrderBy(a => a.SampleDate).ToList();
Note that SampleDate
is a nullable field.
For what I need it more extensive but I like to look through rss
and add milliseconds to the SampleDate
with a foreach.
I tried:
foreach (var r in rss)
{
r.SampleDate = r.SampleDate.Value.AddMilliseconds(1);
}
but get message:
SamplePoint cannot be assigned, it is read-only.
There is a { get; set; }
on it. Is there a problem on how I am assigning?
Upvotes: 0
Views: 423
Reputation: 885
You will need a concrete type to do this as anonymous types (new { ... }
) cannot be modified once created.
public class RssData
{
public DateTime? SampleDate {get; set;}
public string DataValue {get; set;} // use string only if appropriate - I guessed at its type
}
Then, in whatever method you're doing what you're doing...
public void YourMethod()
{
var rss = result.Select(x => new RssData { x.SampleDate, x.DataValue })
.OrderBy(a => a.SampleDate).ToList(); // .ToList() may be redundant here as the foreach below will force the iteration, but that's not really the point of this. :)
foreach(var r in rss)
{
if(r.SampleDate.HasValue)
r.SampleDate = r.SampleDate.Value.AddMilliseconds(1);
}
}
Hope this helps...
Upvotes: 0
Reputation: 37299
You are getting the error because rss
is a list of an anonymous type and not of the type of the items in your result
collection. These anonymous types are immutable and that is why you can't assign the values.
Instead try this:
var rss = result.Select(x => new { SampleDate = x.SampleDate?.AddMilliseconds(1), x.DataValue })
.OrderBy(a => a.SampleDate).ToList();
Notice the use of the Null-conditional operator introduced in C# 6.0
Upvotes: 2