2017-04-10 76 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。谢谢 –