Reputation: 31
I'm sorry most of the program is in Spanish since that's my main language and it's a bit of a mess but it's short.
using System;
using System.Linq;
using System.Collections.Generic;
namespace Tarea_2
{
class Demo
{
static void Main()
{
Console.Write("¿Cuántos números desea entrar? ");
int cun = Int32.Parse(Console.ReadLine());
Console.WriteLine();
Console.WriteLine("Entre "+cun+" números");
Console.WriteLine("Oprima 'Enter' después de cada uno.");
//unaLista recoge los valores directamente del usuario
List<int> unaLista = new List<int>();
for (int i = 0; i < cun; i++)
unaLista.Add(Int32.Parse(Console.ReadLine()));
Console.WriteLine();
Console.Write("¿Qué cantidad desea sumar a cada número? ");
int sum = Int32.Parse(Console.ReadLine());
Console.WriteLine();
//otraLista los copia de unaLista y les suma la variable "sum"
**List<int> otraLista = new List<int>();
otraLista.AddRange(unaLista);**
Mostrar(unaLista);
Mostrar(otraLista);
}//End of Main
public static void Mostrar(List<int> a)
{
foreach (int valor in a)
Console.WriteLine(valor);
Console.WriteLine();
}//End of Mostrar
}//End of Demo
}//End of namespace
Anyway, I'm saving a variable that comes from the user on "sum" that I need to SUM to the total of each number that was copied to "otraLista" through AddRange from "unaLista". Is this possible?
edit: I always do these kind of things with arrays but this was my first time using Lists (since is supposed to be better), so many many thanks, this worked really nice:
List otraLista = unaLista.Select(i => i + sum).ToList();
Expected Results below:
¿Cuántos números desea entrar? 3
Entre 3 números. Oprima 'Enter' después de cada uno.
20
30
40
¿Qué cantidad desea sumar a cada número? 100
20
30
40
120
130
140
Press 'Enter' to finish...
Upvotes: 2
Views: 571
Reputation: 44366
You can do this with LINQ:
otraLista = otraLista.Select(i => i + sum).ToList();
Or if you want to do it before the AddRange, you can skip the new List<int>
and AddRange
and do this instead:
List<int> otraLista = unaLista.Select(i => i + sum).ToList();
Make sure you are
using System.Linq;
Upvotes: 4