C# program that replaces even numbers with the word even
I am trying to write a program that replaces even numbers with the word "EVEN". So far, I have:
List<int> num = new List<int>();
for (int num1 = 0; nu开发者_Python百科m < 101; num++)
{
num.add(num1)
}
foreach(int n in num1)
{
if (n/3)
{
num.Replace("EVEN")
}
}
Is this close or am I far off?
var list = new List<string>();
for (int i = 0; i < 101; i++)
{
string value = (i % 2 == 0) ? "EVEN" : i.ToString();
list.Add(value);
}
In one line:
var list = Enumerable.Range(1, 100).Select(i => (i % 2 == 0) ? "EVEN" : i.ToString()).ToList();
not sure why you are trying to do this, but this should work..:
var num = new List<string>();
for (int n = 0; n < 101; n++)
{
num.Add(n % 2 == 0 ? "EVEN" : n.ToString());
}
Solutions have been provided for constructing a list of strings where each element of the list will be the number if it's odd or "EVEN" if it's even.
If, for some reason, you actually need to take an existing list of int
and perform such a replacement, make sure you understand a fundamental problem: You can't insert the string
"EVEN" into a strongly-typed list of int
.
If you do start with a List<int>
, you'll have to iterate over it and insert the results into a new List<string>
, replacing even numbers with "EVEN" as per @CMP or @Can Gencer's answers.
Enumerable.Range(1, 100)
.Select(n => (n % 2) == 0 ? "EVEN" : n.ToString())
.ToList();
The list of numbers probably should be string if you want to replace with "even".
List<string> numbers = new List<string>();
numbers.Add("1");
numbers.Add("2");
numbers.Add("3");
for (int i = 0; i < numbers.Count; i++)
{
int n = 0;
bool success = int.TryParse(numbers[i], out n);
if (success && n % 2 == 0)
{
numbers[i] = "Even";
}
}
//Output Test Results
foreach (string number in numbers)
{
Console.WriteLine(number);
}
精彩评论