How to generate a list of number in C# - c#

How to create a list of num from 1 to 10
Example:
int[] values = Enumerable.Range(1,max).ToArray();
MessageBox.Show(values+",");
The output should be:
1,2,3,4,5,6,7,8,9,10
Please help

your code is generating array of integers from 1 to 10
int[] values = Enumerable.Range(1,10).ToArray();
but you're displaying them in wrong way (you're trying to cast int array to string), change it to
MessageBox.Show(string.Join(",", values);
string.Join will join your values separating them with ,
In .Net <4.0 you should use (and I believe OP is using one)
MessageBox.Show(string.Join(",", values.Select(x=>x.ToString()).ToArray());

Try like below using the generic version of Join<T>() method.
int[] arr = Enumerable.Range(1, 10).ToArray();
MessageBox.Show(string.Join<int>(",", arr));
Generate 1,2,3,4,5,6,7,8,9,10
(OR) using good old foreach loop
string str = string.Empty;
foreach (int i in arr)
{
str += i.ToString() + ",";
}
MessageBox.Show(str.TrimEnd(','));

List<int> values = Enumerable.Range(1, 10).ToList();
MessageBox.Show(string.Join(",", values.Select(x => x.ToString())));

Related

I need to run command that in string

I have a problem with code.
I want to implement radix sort to numbers on c# by using ling.
I give as input string and give 0 in the start of the number:
foreach(string number in numbers){<br>
if(number.lenth > max_lenth) max_lenth = number.lenth;<br><br>
for(int i = 0; i < numbers.lenth; i++){<br>
while(numbers[i].length < max_lenth) numbers[i] = "0" + numbers[i];<br><br>
after this I need to order by each number in string, but it doesn't work with my loop:
var output = input.OrderBy(x => x[0]);
for (int i = 0; i < max_lenth; i++)
{
output = output.ThenBy(x => x[i]);
}
so I think to create a string that contain "input.OrderBy(x => x[0]);" and add "ThenBy(x => x[i]);"
while max_length - 1 and activate this string that will my result.
How can I implement it?
I can't use ling as a tag because its my first post
If I am understanding your question, you are looking for a solution to the problem you are trying to solve using Linq (by the way, the last letter is a Q, not a G - which is likely why you could not add the tag).
The rest of your question isn't quite clear to me. I've listed possible solutions based on various assumptions:
I am assuming your array is of type string[]. Example:
string[] values = new [] { "708", "4012" };
To sort by alpha-numeric order regardless of numeric value order:
var result = values.OrderBy(value => value);
To sort by numeric value, you can simply change the delegate used in the OrderBy clause assuming your values are small enough:
var result = values.OrderBy(value => Convert.ToInt32(value));
Let us assume though that your numbers are arbitrarily long, and you only want the values in the array as they are (without prepending zeros), and that you want them sorted in integer value order:
string[] values = new [] { "708", "4012" };
int maxLength = values.Max(value => value.Length);
string zerosPad = string
.Join(string.Empty, Enumerable.Repeat<string>("0", maxLength));
var resultEnumerable = values
.Select(value => new
{
ArrayValue = value,
SortValue = zerosPad.Substring(0, maxLength - value.Length) + value
}
)
.OrderBy(item => item.SortValue);
foreach(var result in resultEnumerable)
{
System.Console.WriteLine("{0}\t{1}", result.SortValue, result.ArrayValue);
}
The result of the above code would look like this:
0708 708
4012 4012
Hope this helps!
Try Array.Sort(x) or Array.Sort(x,StringComparer.InvariantCulture).

How can i convert my int array to string array in c#?

I'm new in c# unity. I've to save my array of positions inside firebase for that I'm creating an int array like
int[] positions = new int[] {2, 4, 3};
its working fine but I don't know how can I convert this into string array like "[2, 4, 3]" to save in firebase.
I've searched on google and tried
string stringPositions = string.Join("", positions);
but it completely converts my array into a string like 234. And also how can I encode this string again into an array. Let me know if there is any other approach to do this. thanks!
First of all your question is wrong, you want to convert int array into string.
Use this:
int[] positions = new int[] {2, 4, 3};
string result = "[" + string.Join(",", positions) + "]";
Or this:
int[] positions = new int[] {2, 4, 3};
StringBuilder stb = new StringBuilder();
stb.Append("[");
stb.Append(string.Join(",", positions));
stb.Append("]");
string result = stb.ToString();
Or if you have C#6 or higher:
int[] positions = new int[] {2, 4, 3};
string result = $"[{string.Join(",", positions)}]";
Also if you want to convert back to your int array, for example you can just write your converter:
private int[] ConvertToIntArray(string myCustomString) //myCustomString is in "[1,2,3]" format
{
return myCustomString.Substring(1, myCustomString.Length - 2)
.Split(',')
.Select(s => int.Parse(s))
.ToArray();
}
"[1,2,3,4]"
is a json format of int array. Not string array.
You can use any JSON parser to do this.
I would recommend using JsonUtility which is built in Unity API.
Follow this guide to understand how it works:
Serialize and Deserialize Json and Json Array in Unity
Hope this helps.
Since you are new better use loop
int[] positions = new int[] {2, 4, 3};
string[] s = new string[positions.Length];
for (int x=0; x<positions.Length; i++)
s[x] = positions[x].ToString();
You have to do it manually.
String arrStr = "[";
for ( int i = 0; i < arr.length() - 1; i++) {
arrStr.join(arr[i]);
arrStr.join(",");
}
arrStr.join(arr[arr.length() - 1]);
arrStr.join("]");
Now you will have your array as you desired.
You have asked for a string array but your example is actually just a string that happens to look how you'd declare your int array in code.
For an actual array of strings you'd do what someone else has said and use linq
string[] stringArray = positions.select(p => p.ToString());
This would give you a new array who's item data type would be string .
If you want an actual string of text that looks like what you've asked for
string stringRepresentation = $"[{string.Join(", ", positions)}]";
Or with an old fashioned string format:
string stringRepresentation = string.Format("[{0}]", string.Join(", ", positions);
But just to be clear. This is isn't in depth stuff. Some quick googling and understanding of how to use the string.Join method would have brought you this answer.
So I'm going to l leave you with a pointer towards the trim method on a string and also the split method which should give you everything you need to recreate your int array

Help Needed to convert a C# List into a proper format

I'm a bit new to C# and need help with the following problem
I have a List ticker which contains following values in it
ticker[0] =1
ticker[1] = 122
ticker[2] = 321
.....
ticker[n] = n // where n is some random number
Now the problem is that I need to create an object List which looks like
keys:[[1,66],[122,66],[321,66],.....,[n,66]]
Any help or suggestion is greatly appreciated.
Thanks in Advance
--P
Easy:
var pairs = ticker.Select(x=>new[]{x,66}).ToList();
pairs will be an list of 2-element integer arrays, where each element in your original array is paired with a second value of 66.
You could also use the same statement to create a Tuple (in .NET 4.0) of two integers:
var pairs = ticker.Select(x=>new Tuple<int,int>(x,66)).ToList();
This is a little more O/O; you access the first and second values of the pair using .Value1 and .Value2 instead of [0] and [1].
If you want to create an array of arrays:
int[][] keys = ticker.Select(n => new int[] { n, 66} ).ToArray();
If you want to create a string:
string s = "keys:[" + String.Join(",", ticker.Select(n => "[" + n.ToString() + ",66]")) + "]";
Using Linq, if you want to map the value to the index.
ticker.Select((val, index) => new[] { val, index }).ToList();
If you literally want the number 66 after each item:
ticker.Select(val => new[] { val, 66 }).ToList();
That will create a list of arrays, each the pair of values you wanted.

How to split a number into individual digits in c#? [duplicate]

This question already has answers here:
Is there an easy way to turn an int into an array of ints of each digit?
(11 answers)
Closed 7 years ago.
Say I have 12345.
I'd like individual items for each number. A String would do or even an individual number.
Does the .Split method have an overload for this?
I'd use modulus and a loop.
int[] GetIntArray(int num)
{
List<int> listOfInts = new List<int>();
while(num > 0)
{
listOfInts.Add(num % 10);
num = num / 10;
}
listOfInts.Reverse();
return listOfInts.ToArray();
}
Something like this will work, using Linq:
string result = "12345"
var intList = result.Select(digit => int.Parse(digit.ToString()));
This will give you an IEnumerable list of ints.
If you want an IEnumerable of strings:
var intList = result.Select(digit => digit.ToString());
or if you want a List of strings:
var intList = result.ToList();
Well, a string is an IEnumerable and also implements an indexer, so you can iterate through it or reference each character in the string by index.
The fastest way to get what you want is probably the ToCharArray() method of a String:
var myString = "12345";
var charArray = myString.ToCharArray(); //{'1','2','3','4','5'}
You can then convert each Char to a string, or parse them into bytes or integers. Here's a Linq-y way to do that:
byte[] byteArray = myString.ToCharArray().Select(c=>byte.Parse(c.ToString())).ToArray();
A little more performant if you're using ASCII/Unicode strings:
byte[] byteArray = myString.ToCharArray().Select(c=>(byte)c - 30).ToArray();
That code will only work if you're SURE that each element is a number; otherisw the parsing will throw an exception. A simple Regex that will verify this is true is "^\d+$" (matches a full string consisting of one or more digit characters), used in the Regex.IsMatch() static method.
You can simply do:
"123456".Select(q => new string(q,1)).ToArray();
to have an enumerable of integers, as per comment request, you can:
"123456".Select(q => int.Parse(new string(q,1))).ToArray();
It is a little weak since it assumes the string actually contains numbers.
Here is some code that might help you out. Strings can be treated as an array of characters
string numbers = "12345";
int[] intArray = new int[numbers.Length];
for (int i=0; i < numbers.Length; i++)
{
intArray[i] = int.Parse(numbers[i]);
}
Substring and Join methods are usable for this statement.
string no = "12345";
string [] numberArray = new string[no.Length];
int counter = 0;
for (int i = 0; i < no.Length; i++)
{
numberArray[i] = no.Substring(counter, 1); // 1 is split length
counter++;
}
Console.WriteLine(string.Join(" ", numberArray)); //output >>> 0 1 2 3 4 5

How can I count the unique numbers in an array without rearranging the array elements?

I am having trouble counting the unique values in an array, and I need to do so without rearranging the array elements.
How can I accomplish this?
If you have .NET 3.5 you can easily achieve this with LINQ via:
int numberOfElements = myArray.Distinct().Count();
Non LINQ:
List<int> uniqueValues = new List<int>();
for(int i = 0; i < myArray.Length; ++i)
{
if(!uniqueValues.Contains(myArray[i]))
uniqueValues.Add(myArray[i]);
}
int numberOfElements = uniqueValues.Count;
This is a far more efficient non LINQ implementation.
var array = new int[] { 1, 2, 3, 3, 3, 4 };
// .Net 3.0 - use Dictionary<int, bool>
// .Net 1.1 - use Hashtable
var set = new HashSet<int>();
foreach (var item in array) {
if (!set.Contains(item)) set.Add(item);
}
Console.WriteLine("There are {0} distinct values. ", set.Count);
O(n) running time max_value memory usage
boolean[] data = new boolean[maxValue];
for (int n : list) {
if (data[n]) counter++
else data[n] = true;
}
Should only the distinct values be counted or should each number in the array be counted (e.g. "number 5 is contained 3 times")?
The second requirement can be fulfilled with the starting steps of the counting sort algorithm.
It would be something like this:
build a set where the index/key is
the element to be counted
a key is connected to a variable which holds the number of occurences
of the key element
iterate the array
increment value of key(array[index])
Regards

Categories