开发者

C# Calculate items in List<int> values vertically

开发者 https://www.devze.com 2023-01-03 10:40 出处:网络
I have a list of int values some thing like below (upper bound and lower bounds are dynamic) 开发者_运维百科1, 2, 3

I have a list of int values some thing like below (upper bound and lower bounds are dynamic)

开发者_运维百科1, 2, 3
4, 6, 0
5, 7, 1

I want to calculate the column values in vertical wise like

1 + 4 + 5 = 10
2 + 6 + 7 = 15
3 + 0 + 1 = 4

Expected Result = 10,15,4

Any help would be appreciated

Thanks

Deepu


Here's the input data using array literals, but the subsequent code works exactly the same on arrays or lists.

var grid = new []
           {
               new [] {1, 2, 3},
               new [] {4, 6, 0},
               new [] {5, 7, 1},
           };

Now produce a sequence with one item for each column (take the number of elements in the shortest row), in which the value of the item is the sum of the row[column] value:

var totals = Enumerable.Range(0, grid.Min(row => row.Count()))
                       .Select(column => grid.Sum(row => row[column]));

Print that:

foreach (var total in totals)
    Console.WriteLine(total);


If you use a 2D array you can just sum the first, second,... column of each row.

If you use a 1D array you can simply use a modulo:

int[] results = new results[colCount];
for(int i=0, i<list.Count; list++)
{
  results[i%colCount] += list[i];
}


Do you have to use a "List"-object? Elseway, I would use a twodimensional array.

Otherwise, you simply could try, how to reach rows and columns separatly, so you can add the numbers within a simply for-loop. It depends on the methods of the List-object.


Quite inflexible based on the question, but how about:

int ans = 0;
for(int i = 0; i < list.length; i+=3)
{
    ans+= list[i];
}

You could either run the same thing 3 times with a different initial iterator value, or put the whole thing in another loop with startValue as an interator that runs 3 times.

Having said this, you may want to a) look at a different way of storing your data if, indeed they are in a single list b) look at more flexible ways to to this or wrap in to a function which allows you to take in to account different column numbers etc...

Cheers, Adam

0

精彩评论

暂无评论...
验证码 换一张
取 消