+ 1
C# - search for better ways for char[] to int[] convert.
I'm someone who always want to use less code but I never come around using much by char[] to int[] convert. Any other methodes than my? Here some codes where I had that problem. https://code.sololearn.com/c1W5WyeKwY6J/?ref=app https://code.sololearn.com/cxs6i7xhpF8D/?ref=app P.s. : The Kaprekar's constant code should be more readable now cleaned a bit.
20 Antworten
+ 2
You could also use linq Select:
list.Select(x => int.Parse(x))
It returns an IEnumerable<int>
But be aware of exceptions if the string can't be parsed.
edit:
If you want to use char collections you need to convert them to strings when passing them to Parse:
list.Select(x => int.Parse(x.ToString()))
+ 3
There is ConvertAll() but Idk whether it was a "better way"
https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.convertall?view=net-6.0
+ 1
Ipang I already tho of using it but I don't rly get it before I use them I still need to read a bit.
But still thanks for the answer.
+ 1
Here is an example for the ternary approach you asked for. If you don't want to use another number as fallback value you could use a nullable int:
https://code.sololearn.com/cEY5EBL54fRQ/?ref=app
+ 1
Option A:
Create a custom comparer
public class SampleComp : IComparer<int?>
{
public int Compare(int? a, int? b)
{
// compare logic
// return 0 => equal
-1 => lower
1 => higher
}
}
Option B:
(b ?? int.MinValue).CompareTo(a ?? int.MinValue))
(this is getting a bit out of hands with so many edge cases 😂)
edit: also keep in mind, that sort takes care of null values. They get sorted before all other elements. And reverse also reverses them correctly.
If you somehow get null values and don't want them you can also just filter the list and get rid of them
-> list.Where(x => x != null)
+ 1
Alex Thanks I would still Most likely take Option B by smaller Codes. And for 0-case I want to redo my Kraprekar's constant code so I still need them but still good to know.
edit: When I want to delete all zeros I rather go with List.RemoveAll(x => x.Equals(0))
+ 1
Then you'll get an exception if a value is null. If you are sure that the input is a digit you can use Parse instead of TryParse. Or you use try-catch for the input part.
List<int> constant;
try
{
constant = Console.ReadLine()
.ToCharArray()
.Select(x => int.Parse(x.ToString()))
.ToList();
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine("Digits only!");
return;
}
0
Thanks both of you. I will try all the named methodes in my next codes.
Note: I'm a bit slow with the courses so I didn't come much around Error Handling with as example Try{ } catch { }.
0
There is also a TryParse, but it doesn't return the parsed value, but a bool as indicator if the parse was successful.
var str = "100";
if(int.TryParse(str, out int number))
{
// parse was successfull
}
else
{
// parse failed
}
0
Also could I just do as example
var Input = "1000";
var str = int.TryParse(input, out int number) ? number : 0;
?
0
Alex Thanks for the edit remark at the end, I tested it before and just used Convert.ToInt32() -48. Thanks for that I rather use that methode.
0
Alex Good Code tho I understand some parts with the '?' (multiply). But I now Made my own Code with that Methode.
https://code.sololearn.com/cCL1nV1W9hPG/?ref=app
Question: Why does a <int?> List have no compare methode?
0
I don't get the question, sorry. Could you explain what you mean?
0
The List I needed to make isn't int but int? else I couldn't use the TryParse Methode like that. And int? seems to have no CompareTo Methode like int. I tried using List.Sort((a, b) => b.CompareTo(a)); but didn't work
0
Alex tho I need to say that I rather would like to know about another desending Sort other than that.
Note: I mean Methode except List.Reverse() and self Made sort
0
I wrote that Code now with the desending Methode
https://code.sololearn.com/cCL1nV1W9hPG/?ref=app
0
Edit: We can avoid all that Edge cases we can write.
(a, b) => b.Value.CompareTo(a.Value)
Here in a Code again.
https://code.sololearn.com/c146OxMj7R2s/?ref=app
0
I now made it so because I want to Break it after writing it wrong one time:
if(constant.Contains(null)) Console.WriteLine("Your input don't just contain digits");
else
{
constant.Sort((a,b) => b.Value.CompareTo(a.Value));
constant.ForEach(x => Console.Write(x.ToString()));
}
I rather Bond to familiar methodes so I always prefer using if-else or when I want to let the program take input until it's correct I would use while()
edit: a.HasValue have the same effect as int.MinValue() and also don't need Error Handling
0
Try Int32.Parse(Convert.ToString(char[i]))
0
Leonid Amvrosov I tried to find a better way that to use always for-loops.
Your Methode:
for (int i = 0; i> charArr.Length; i++) List.Add(int.Parse(char[i].ToString()));