This question already has answers here:
Convert a list to a string in C#
(14 answers)
Closed 9 months ago.
I am a mere beginner and I am trying to learn a bit of LINQ. I have a list of values and I want to receive a different list based on some computation. For example, the below is often quoted in various examples across the Internet:
IEnumerable<int> squares = Enumerable.Range(1, 10).Select(x => x * x);
here the "computation" is done by simply multiplying a member of the original list by itself.
I wanted to actually use a method that returns a string and takes x as an argument.
Here is the code I wrote:
namespace mytests{
class program {
static void Main (string[] args)
{
List<string> nums = new List<string>();
nums.Add("999");
nums.Add("888");
nums.Add("777");
IEnumerable<string> strings = nums.AsEnumerable().Select(num => GetStrings(num));
Console.WriteLine(strings.ToString());
}
private static string GetStrings (string num){
if (num == "999")
return "US";
else if (num == "888")
{
return "GB";
}
else
{
return "PL";
}
}
}
}
It compiles but when debugging, the method GetStrings is never accessed and the strings object does not have any members. I was expecting it to return "US", "GB", "PL".
Any advice on what I could be doing wrong?
Thanks.
IEnumerable<string>.ToString() method does not work as you expected. Result will be
System.Collections.Generic.List`1[System.String]
If you want to see the values which are held in the collection, you should create iteration.
foreach (var i in strings)
Console.WriteLine(i);
This line does two things for you. One of them is writing the values which are held in the collection to console. The other operation is iterating the collection. During iteration, values are needed and linq will execute the necessary operation (in your case GetStrings method).
Currently your code does not use the collection values, so the code does not evaluate the values and does not trigger GetStrings method.
This question already has answers here:
How to stop the execution of a method after a specific time?
(2 answers)
Run and stop a method for a minute
(6 answers)
Closed 2 years ago.
I wanted to know if there was any way I could cause a method to "time-out" or stop executing if nothing is returned. For example, in the code provided below, I'm passing a BigInteger through a method that determines if an integer is probable prime or not. When I call the method, I am using an array of Big Integers to test the method several times.
class PrimeChecker {
public static bool isPrime(BigInteger num) {
if (num <= 1)
{
return false;
}
if (num == 2)
{
return true;
}
for (int i = 3; i <= num / 2; ++i)
{
if (num % i == 0)
{
return false;
}
}
return true;
}
}
}
However I am running in to an issue where some instances of num, such as:
35201546659608842026088328007565866231962578784643756647773109869245232364730066609837018108561065242031153677 (is Prime)
are stuck calculating in what feels like forever. Is there a way, either in my main or in the class itself, that I can stop this function after a certain period of time and move on to the next Big Integer in the array.
*I understand that the class itself may not be perfect and is most likely what is causing this test to be looping forever. However, I just wanted to see if there was any way to stop the function if it is calculating for x seconds/minutes.
This question already has answers here:
How can I return NULL from a generic method in C#?
(13 answers)
Closed 2 years ago.
In my Data Structures class I've been tasked with creating an ArrayList of generic objects of a given type. This is essentially a class that behaves like an array with some extra functionality attached. It looks something like this.
public class GenericArray<T>
{
// The array
private T[] array;
private int size;
// Constructor
public GenericArray(int arrsize)
{
size = arrsize;
array = new T[size + 1];
}
// Array methods
public T getItem(int index)
{
return array[index];
}
public int getCount()
{
int count = 0;
for(int i = 0; i < array.Length; ++i)
{
if(array[i] != null)
count++;
}
size = count;
return count;
}
}
We're required to create the various methods by which you interact with the array. I'm having a particular problem when it comes to deleting items from the array. I have a deleteLast method which I assumed would simply set the last item to null, like so:
public void deleteLast()
{
int i = this.getCount()-1;
array[i] = null;
}
However I am getting the error that I cannot convert the parameter to null, as T may not be a nullable value type, which makes sense. However, I don't know how to remove them otherwise. I can't find any useful information on this through Google, so I've come to Stack Overflow.
Any help is appreciated. Thanks :)
Why don't you use List<T> instead of T[] ? That should easily solve all your problems!
You haven't handled cases around array size changes (for growing and reducing array size), enumeration, etc. Ideally I would implement IEnumerable and implement rest of the functions!
This question already has answers here:
Directly modifying List<T> elements
(6 answers)
Closed 8 years ago.
I am writing a function which is passed in a list which is partially filled. I'd like to set some of the fields within the list inside this function. I thought that passing it as a reference would allow me to do this, however, I get the following error:
Error 1 Cannot modify the return value of 'System.Collections.Generic.List.this[int]' because it is not a variable
I am wondering what I might need to do to tell C# that I wish to have the option of modifying the contents of the list.
Here is a summarized version of my code:
public static void Determine_RTMM_Descriptor(ref List<Struct_Descriptor_Type> symbols, string Dwarf_Output_Filename)
{
...
lines = System.IO.File.ReadAllLines(Dwarf_Output_Filename);
//loop on symbol names
for (int idx = 0; idx < symbols.Count; idx++)
{
if(symbols[idx].size == 0)
symbols[idx].size = (int)new System.ComponentModel.Int32Converter().ConvertFromString(split_line[DwarfInterface.SIZE_INDEX]);
...
}
Thanks in advance for any help.
The underlying issue here is that you have a list of value types. When you use the indexer of the list to get an item from the list you are getting a copy of that type. The code symbols[idx] is the value of that item. It is not a variable representing that item, as the error message is telling you.
You're trying to mutate the size of the copy, which will have no effect on the item of the list. This is such a common mistake that the compiler even makes this an error.
If you really are sure that you want to have a mutable value type (hint: you aren't, and you shouldn't have one; you almost certainly just want to have a class here to avoid this problem entirely) then you would need to get the value of the item, mutate it, and then set the item again:
if(symbols[idx].size == 0)
{
var symbol = symbols[idx];
symbol.size = 42;
symbols[idx] = symbol;
}
Your return type on the function is "void" when you should set the return type to the list. That should allow you to change it and return it modified.
Been trying to solve this for 2 days now and I just can't get it to work! The programs layout has to stay the same (part of the challenge). Really bugging me and hoping somebody could shed some light...
I keep getting the following error:
Use of unassigned local variable 'countOfFizz'
Use of unassigned local variable 'countOfBuzz'
Use of unassigned local variable 'countOfFizzBuzz'
Use of unassigned local variable 'countOfPrime'
On these lines:
fb.IsFizz(input, countOfFizz);
fb.IsFizz(input, countOfBuzz);
fb.IsFizz(input, countOfFizzBuzz);
fb.IsFizz(input, countOfPrime);
and here is the full code. (again apologies if its poor coding, its basics and the layout has been supplied already).
class FizzBuzz
{
public static void Main()
{
int input;
string enter;
int countOfFizz;
int countOfBuzz;
int countOfFizzBuzz;
int countOfPrime;
Console.WriteLine("Please enter a number: ");
enter = Console.ReadLine();
input = int.Parse(enter);
while (input != 0)
{
Console.WriteLine("Please enter a number: ");
enter = Console.ReadLine();
input = int.Parse(enter);
FizzBuzz fb = new FizzBuzz();
fb.IsFizz(input, countOfFizz);
FizzBuzz fb1 = new FizzBuzz();
fb1.IsBuzz(input, countOfBuzz);
FizzBuzz fb2 = new FizzBuzz();
fb2.IsFizzBuzz(input, countOfFizzBuzz);
FizzBuzz fb3 = new FizzBuzz();
fb3.IsPrime(input, countOfPrime);
FizzBuzz fb4 = new FizzBuzz();
fb4.TotalFizz(countOfFizz);
FizzBuzz fb5 = new FizzBuzz();
fb5.TotalBuzz(countOfBuzz);
FizzBuzz fb6 = new FizzBuzz();
fb6.TotalFizzBuzz(countOfFizzBuzz);
FizzBuzz fb7 = new FizzBuzz();
fb7.TotalPrime(countOfPrime);
}
Console.WriteLine("Finished.");
}
public bool IsFizz(int input, int countOfFizz)
{
if (input % 9 == 0)
{
Console.WriteLine("Fizz");
countOfFizz++;
return true;
}
return false;
}
public bool IsBuzz(int input, int countOfBuzz)
{
if (input % 13 == 0)
{
Console.WriteLine("Buzz");
countOfBuzz++;
return true;
}
return false;
}
public bool IsFizzBuzz(int input, int countOfFizzBuzz)
{
if (input % 9 == 0 && input % 13 == 0)
{
Console.WriteLine("FizzBuzz");
countOfFizzBuzz++;
return true;
}
return false;
}
public bool IsPrime(int input, int countOfPrime)
{
for (int i = 2; i < input; i++)
{
if (input % i == 0 && i != input)
{
return false;
}
}
Console.WriteLine("Prime");
countOfPrime++;
return true;
}
public void BeginTesting(int countOfFizz, int countOfBuzz, int countOfFizzBuzz, int countOfPrime)
{
countOfFizz = 0;
countOfBuzz = 0;
countOfFizzBuzz = 0;
countOfPrime = 0;
}
public int TotalFizz(int countOfFizz)
{
Console.WriteLine("Number of Fizz: ");
return countOfFizz;
}
public int TotalBuzz(int countOfBuzz)
{
Console.WriteLine("Number of Buzz: ");
return countOfBuzz;
}
public int TotalFizzBuzz(int countOfFizzBuzz)
{
Console.WriteLine("Number of FizzBuzz: ");
return countOfFizzBuzz;
}
public int TotalPrime(int countOfPrime)
{
Console.WriteLine("Number of Prime: ");
return countOfPrime;
}
}
The problem is that you are passing ints to the methods, when an int (or float, bool, etc.) is passed to a method it is copied, it is not passed as a reference variable. Therefore, the countOfBuzz you change within a method is not the same as the one in the main method.
To solve this, don't pass those parameters to the methods. Instead, change the scope of those variables to be inside the class instead of inside the main method.
Also, it is good practice to initialize the variables to zero (local variables within methods need to be initialized, otherwise you get that message you asked about).
As Simon already explained in his answer, integers are value types and all value types are always passed by value (by default). This means that when you call for example IsFizz with the countOfFizz then all that happens is that the value of that variable is passed to the function which then has its own variable with a copy of the value. So when the function changes the value, then only that local variable’s value changed but that change will never make it to the original variable.
One way to solve this would be to explicitely pass those variables by reference. You can do this by using ref int countOfFizz in the function signature for the parameter (i.e. add the ref keyword). However, I do not recommend you to do this as it will not provide a state the FizzBuzz class was likely to have.
So, in object oriented programming, you create objects which hold a state. In your case, the FizzBuzz is the class, the type of those objects. Now if we think about it, and take into account that you apparently want to keep count of the number of Fizz/Buzz/FizzBuzz cases, it makes sense to have those counts contained within the object.
So first of all, you should make those countOfX variables instance variables that are bound to the object.
Looking at the IsFizz etc. methods, they are all supposed to return a boolean value. So it’s likely that they were originally only meant to check the input and return true or false depending on if the check succeeded or not. Here we can also increment our counters when we find a falue. So in the end, those methods should only take the input, perform the check, increment their counter and return the check result.
The TotalX methods can then simply return the current counter results, while the BeginTesting method can reset them to zero (without taking any parameters).
Finally, in the Main function you want to create only a single instance of FizzBuzz so we can share the state during the whole duration of the program. You should check the return values for the IsX methods and print the appropriate response here (often you don’t want class types to arbitrarily print stuff but handle that in a different layer—in your case the console application that happens in the Main function).
As a final note, I would like you to know that I’m interpreting a lot into the original task here and cannot perfectly say what the original intention behind this code was. From my point of view it looks a bit ridiculous to do it like that. The FizzBuzz problem, even in this changed instance, is a simple problem aimed to show if a person is capable of basic programming-related thinking. It’s not necessarily meant to be a problem to work on in a complex object oriented manner, but just like the typical “Hello World” there seem to be people who like over-generalizing it in a way to make it terribly complex for fun or practice. I’m not really agreeing that this FizzBuzz instance with that predefined base code is either generalized nor fun nor a good practice. But again, this is just my opinion.
And finally a last hint to complete this “correctly”: The output “FizzBuzz” is the combination of both conditionals for “Fizz” and ”Buzz”. Meaning that if a number qualifies for “FizzBuzz” it also does so for the individual ones. So you should make sure that the check for the individual ones either explicitely prevent the “FizzBuzz” combination to match, or you check for the combined one first and abort further checks if it matches.
Initialize the variables might do the trick for you:
int countOfFizz = 0;
int countOfBuzz = 0;
int countOfFizzBuzz = 0;
int countOfPrime = 0;
Remove the parameter (countOfFizz) from IsFizz, and it should work. Do the same for other similar methods.
public bool IsFizz(int input)
{
if (input % 9 == 0)
{
Console.WriteLine("Fizz");
countOfFizz++;
return true;
}
return false;
}