2017-04-10 78 views
0

這是類我有我怎樣才能獲得類的屬性值

public class Income 
    { 
     public string Code { get; set; } 
     public int Month1 { get; set; } 
     public int Month2 { get; set; } 
     public int Month3 { get; set; } 
     public int Month4 { get; set; } 
     public int Month5 { get; set; } 
     public List<Income> income { get; set; } 

    } 

在其他類

List<Income> incomeList = new List<Income>(); 

//repeat twice 
Income obj = new Income(); 
obj.Month1 = 200; 
obj.Month2 = 150; 
... 
IncomeList.Add(obj); 
obj.income = IncomeList; 

現在我想找回那些保存在 列表中的每個新對象的循環中的月份。 到目前爲止

Int[] results = obj.income 
    .Select(x=> new 
    { 
     x.Month1, 
     x.Month2, 
     x.Month3, 
     x.Month4, 
     x.Month5 
    }) 
    .ToArray(); 

這是我需要添加的總個月,每一個獨特的對象。 得到所有Months1,個月2總...

double totals[] = new double[5]; 
for (int i=0;i<results.length;i++) 
{ 
    totals[i] += results[i]; // I get the first object reference 
    // I want Moth1,Month2 ... to be in an indexed array where 
    // if i want Month1 i would access similar to : results[index]; 
} 
+0

不確定我100%清楚你正在做什麼。但是如果你想讓這5個屬性在列表中,你能簡單地將一個屬性添加到該類中,該屬性將這些屬性值作爲列表返回? – David

+0

難道你不想讓'public int [] months = new int [5]'而不是這5個'int MonthX'嗎? –

+0

@David我會這麼做 –

回答

0

好了,下面的代碼將伸出的對象列表。每個對象都有一個名爲「Months」的屬性,它是月份值的int[]

這是否做你所需要的?

void Main() 
{ 

    var incomeList = new List<Income>(); 
    Income obj = new Income(); 
    obj.Month1 = 200; 
    obj.Month2 = 150; 

    incomeList.Add(obj); 

    var results = incomeList 
     .Select(x => new 
     { 
      Months = new int[] 
      { 
       x.Month1, 
       x.Month2, 
       x.Month3, 
       x.Month4, 
       x.Month5 
      } 
     }) 
    .ToArray(); 


    for (int i = 0; i < results.Length; i++) 
    { 
     var testResults = results[i]; 
     Console.WriteLine($"Month 1: {testResults.Months[0]}"); 
     Console.WriteLine($"Month 2: {testResults.Months[1]}"); 
     Console.WriteLine($"Month 3: {testResults.Months[2]}"); 
     Console.WriteLine($"Month 4: {testResults.Months[3]}"); 
     Console.WriteLine($"Month 5: {testResults.Months[4]}"); 
    } 
} 

但是,考慮到您在發佈的代碼中的評論,我認爲你想把它變成一個2維數組。如果是這樣,只需投射出一個int[]

void Main() 
{ 
    var incomeList = new List<Income>(); 
    Income obj = new Income(); 
    obj.Month1 = 200; 
    obj.Month2 = 150; 

    incomeList.Add(obj); 

    int[][] results = incomeList 
     .Select(x => new int[] 
     { 
      x.Month1, 
      x.Month2, 
      x.Month3, 
      x.Month4, 
      x.Month5 
     }) 
    .ToArray(); 


    for (int i = 0; i < results.Length; i++) 
    { 
     var testResults = results[i]; 
     Console.WriteLine($"Month 1: {testResults[0]}"); 
     Console.WriteLine($"Month 2: {testResults[1]}"); 
     Console.WriteLine($"Month 3: {testResults[2]}"); 
     Console.WriteLine($"Month 4: {testResults[3]}"); 
     Console.WriteLine($"Month 5: {testResults[4]}"); 
    } 
} 
+0

int [] [] results = incomeList ...這個工作結果[objectRef1] [index0]回顧200。謝謝 –