LINQPAD - How do I set values to parameters when using Select after reading in lines from a file

StackOverflow https://stackoverflow.com/questions/22401825

  •  14-06-2023
  •  | 
  •  

Вопрос

I have the following piece of code which reads in lines from a csv file, and splits by the comma delimiter and stores the ones I am interested in as Period and Payout. However when I want to modify values, i.e. add to them, I am unable to do so because the type has not been specified.

I get the following error: "Property or indexer 'AnonymousType#1Payout' cannot be assigned to -- it is read only"

So basically my question is how do I specify the type of the variables when selecting them? Period is type int (i.e. 6553) and Payout is type double (i.e. 2.922266175000004E7)

var values = File.ReadLines(path).Skip(1)
      .Select(x => x.Split(','))
      .Where(x => x[0] != string.Empty)
      .Select(x => new { Period = x[0], Payout = x[4] })
      .ToList();
Это было полезно?

Решение

Anonymous types are read-only.

So I can't do this:

var x = new { y = 1, z = "Hello" };
x.z = "Goodbye";

However, if I have a list of anonymous variables then I could do this:

var values = File.ReadLines(path)
      .Skip(1)
      .Select(x => x.Split(','))
      .Where(x => x[0] != string.Empty)
      .Select(x => new { Period = x[0], Payout = x[4] })
      .ToList();

values[0] = new { Period = values[0].Period + 1, Payout = values[0].Payout * 2 };
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top