Trouble converting string into List<int> - c#

I have a string that looks like "34,45,74,23" and is dynamically generated. How do I convert this into a List?
var y = numString();
y.ToList();

This should give you a List<int>.
str.Split(',').Select(int.Parse).ToList();
If you are not sure that all strings are parsable to int, or your string contains multiple commas like 23,,24,25 or invalid charachters you can use Where to filter the sequence first:
var numbers = str.Split(',').Where(x => x.All(char.IsDigit)).Select(int.Parse);
Or you can use TryParse:
var numbers = str.Split(',').Select(x =>
{
int result;
if (int.TryParse(x, out result)) return result;
return int.MinValue;
}).Where(x => x != int.MinValue).ToList();
Probably, TryParse is the best option because char.IsDigit returns true for all digits, not just (0-9).

Using Linq:
var numbers = y.Split(',').Select(num => int.Parse(num)).ToList();

This should do it for you
string source = "34,45,74,23";
var stringArray = source.Split(',');
var intArray = stringArray.Select(x => Convert.ToInt32(x)).ToList();

If you are sure that the format is valid you can use Array.ConvertAll and the List<T> constructor which is more efficient:
string[] numbers = "34,45,74,23".Split(',');
var list = new List<int>(Array.ConvertAll(numbers, int.Parse));

Related

Get values from a comma separated string containing less than a value

I am attempting to compare a comma separated string against a decimal variable and find only the amounts less than my variable.
The problem I'm having is my string looks like so:
1usd,5usd,10usd,20usd
I was able to separate the string into a collection by using the comma separator and regex split, but I don't think this is the best approach since I need to check just the value and reconstruct with the us and comma seperation.
A real world example my program will be handling is
decimal changeAvil = 10
notesSet = 1usd,5usd,10usd,20usd
Result should be notesSet = 1usd,5usd
Its not the prettiest code that has ever been written, but is does the job.
I use Linq to select the prefixes of the strings that are numbers, and then compare these to the value of changeAvil.
using System;
using System.Linq;
namespace stack
{
class Program
{
static void Main(string[] args)
{
decimal changeAvil = 10;
var noteSet = "1usd,5usd,10usd,20usd";
var notes = noteSet.Split(',');
var dict =
notes.ToDictionary(
x => int.Parse(new string(x.TakeWhile(c => char.IsNumber(c))
.ToArray())), // key
x => x); // value
var selection = dict.Where(kvp => kvp.Key <= changeAvil)
.Select(kvp => kvp.Value)
.ToList();
foreach (var s in selection) {
Console.WriteLine(s);
}
}
}
}
The solution returns 1usd, 5usd, and 10usd. If your do not want 10usd to be part of the result change kvp.Key <= changeAvil to kvp.Key < changeAvil in the Where clause of the Linq expression.
You can use split command and remove the letters 'usd' and then iterate through the array and compare
decimal changeAvil = 10
notesSet = 1usd,5usd,10usd,20usd
string noteset_new = noteset.Replace('usd',''); //remove usd
string[] noteset_array = noteset_new.split[',']; //split in to array
now you can iterate the above noteset_array and do what every you want to do.
Using replace and split on the string is using two iterations through the strings characters.
A better way to get the array will be to first add a comma to the end of the string and then use split:
notesSet = 1usd,5usd,10usd,20usd
string[] noteset_array = (notesSet + ',').split['usd,']; //split in to array

How to remove comma separated duplicated string values and get last two values

I want to remove comma separated duplicate string values like :
String str = "2,4,3,12,25,2,4,3,6,2,2,2";
And i want to output like this:
String str1 = "6,2";
please tell how to do this i'll my self but i can't solve this
A wild ride with Linq. Probably there is a better way, but this is the first one I could think of.
string str = "2,4,3,12,25,2,4,3,6,2,2,2";
List<string> uniques = str.Split(',').Reverse().Distinct().Take(2).Reverse().ToList();
string newStr = string.Join(",", uniques);
Console.WriteLine(newStr);
Split the string at the comma to get the sequence
Apply the Reverse op, you get 2 2 2 6 .... 4 2
Apply the Distinct, you get 2,6,3,4,25,12
Take the first 2 elements (2,6)
Reverse them 6,2
Join in a new string with the comma sep.
Pretty basic but works in your case
String str = "2,4,3,12,25,2,4,3,6,2,2,2";
String[] arr = str.Split(',');
String penultimate = "";
String ultimate = "";
for (int i = 0; i < arr.Length; i++)
{
if (arr[i] != ultimate)
{
penultimate = ultimate;
ultimate = arr[i];
}
}
Console.WriteLine("{0},{1}", penultimate, ultimate);
Here is a suggestion:
string item = "";
var lastTwoUnique= str.Split(',') //split the string on ,
//now, take the next element from the array as long as it's
//not equal to the previous element (which we store in item)
.Where((st) => st==item ? false : (item = st) == item) //** see comment below
.Reverse() //reverse collection
.Take(2) //take two (two last)
.Reverse() //reverse back
.ToList(); //make it a list
var answer = string.Join(",", lastTwoUnique);
This solution keeps the data intact, so if you want you could store the unique list, then do many queries on that list. Solutions using Distinct() will, for instance, not keep every occurrence of 2 in the list.
This solution has the intermediate result (after Where) of: 2,4,3,12,25,2,4,3,6,2. While distinct will be:2,4,3,12,25,6
** The line .Where((st) => st==item ? false : (item = st) == item) may seem odd, so let me explain:
Where takes a lambda function that returns true for items that should be taken, and false for the items that should be ignored. So st will become each sub string from the Split.
Now, let's investigate the actual function:
st==item //is this st equal to the previous item?
? false //then return false
: (item = st) == item //if it's not equal, then assign `item` to the current `st`
//and compare that to item and get `true`
You could use the .Distinct() extension method.
String str = "2,4,3,12,25,2,4,3,6,2,2,2";
var oldArray=str.Split(',').Reverse();
var collectionWithDistinctElements = oldArray.Distinct().ToArray();
var reverse=collectionWithDistinctElements.Reverse();
//take two element
var twoElements=reverse.ToList().Take(2);
//last join them
var resultArray=string.Join(",", twoElements);
Another solution, which I've attempted to keep quite simple:
String str = "2,4,3,12,25,2,4,3,6,2,2,2";
var holder = new string[2];
foreach (var x in str.Split(','))
{
if(holder.Last() != x)
{
holder[0] = holder[1];
holder[1] = x;
}
}
var result = string.Join(",", holder);
This will iterate over the comma-separated items, all the time keeping the two last seen distinct items in holder.
String str = "2,4,3,12,25,2,4,3,6,2,2,2";
string str = s1;
var uniques = str.Split(',').Reverse().Distinct().Take(3).Reverse().Take(2).ToList();
string newStr = string.Join(",", uniques.ToArray());
This will give me correct output that is 3,6 thats i want.
Thanks to all the Guys that give me ans.
This will definitely work
string str = "2,4,3,12,25,2,4,3,6,2,2,2";
List<string> uniques = new List<string>()
uniques = str.Split(',').Reverse().Distinct().Take(2).Reverse().ToList();
string newStr = string.Join(",", uniques);

How to check if string contains a string in string array

edit: the order might change as you can see in the below example, both string have same name but different order....
How would you go after checking to see if the both string array match?
the below code returns true but in a reality its should return false since I have extra string array in the _check
what i am trying to achieve is to check to see if both string array have same number of strings.
string _exists = "Adults,Men,Women,Boys";
string _check = "Men,Women,Boys,Adults,fail";
if (_exists.All(s => _check.Contains(s))) //tried Equal
{
return true;
}
else
{
return false;
}
string _exists = "Adults,Men,Women,Boys";
string _check = "Men,Women,Boys,Adults,fail";
bool b = _exists.Split(',').OrderBy(s=>s)
.SequenceEqual(_check.Split(',').OrderBy(s=>s));
Those are not array of strings, but two strings.
So, you actually need to split them into substrings before checking for the content equality.
You can do in this way:
string _exists = "Adults,Men,Women,Boys";
string _check = "Men,Women,Boys,Adults,fail";
var checks = _check.Split(',');
var exists = _exists.Split(',');
bool stringsEqual = checks.OrderBy(x => x).SequenceEqual(exists.OrderBy(x => x));
To speed up a bit some special cases, you could check for length before calling the LINQ code (avoiding the two OrderBy's in case of different lengths). Furthermore, to save memory, you could use in-place sort on the splits arrays, i.e. :
string _exists = "Adults,Men,Women,Boys";
string _check = "Men,Women,Boys,Adults,fail";
var checks = _check.Split(',');
var exists = _exists.Split(',');
if(checks.Length != exists.Length)
return false;
Array.Sort(checks);
Array.Sort(exists);
if (checks.SequenceEqual(exists))
return true;
return false;
Obviously these optimizations are useful only if your strings are really long, otherwise you can simply go with the LINQ one-liner.
try
return (_exists.Length == _check.Length);
That will check if the string arrays are the same length, but not necessarily the same values.
If you want to compare the arrays to see if they are exactly the same you will need to do the above first, then most likely sort the arrays into A-Z order, and compare each element
NOTE: This is unnecessary...
if (_exists.All(s => _check.Contains(s))) //tried Equal
{
return true;
}
else
{
return false;
}
...you can do this, and it's more elegant...
return (_exists.All(s => _check.Contains(s)));
If you want to see if the number of substrings separated by a comma is the same, then use this.
public bool StringsHaveSameNumberOfSubstring(string _exists, string _check)
{
return (_exists.Split(',').Length == _check.Split(',').Length);
}
This is what I understood from your question.
Split the strings to make two list, and later compare them using Linq to Objects
string _exists = "Adults,Men,Women,Boys";
string _check = "Men,Women,Boys,Adults,fail";
List<string> exists = new List<string>(_exists.Split(new char[] { ',' }));
List<string> check = new List<string>(_check.Split(new char[] { ',' }));
foreach(string toCheck in check){
if(exists.Contains(toCheck)){
//do things
}
}
If you just want to count strings try:
bool sameAmountOfStrings = _exists.Count(c => c.Equals(',')) == _check.Count(c => c.Equals(,));
First of all you need to split the strings to get arrays and sort them
var ary1 = _existing.Split(',').Trim().OrderBy(x => x);
var ary2 = _check.Split(',').Trim().OrderBy(x => x);
Now you can use 'SequenceEquals' to compare the Enumerables
var result = ary1.SequenceEquals(ary2);
SeqenceEquals compares the position and value, so if you want to detect positional changes as well, remoce the OrderBy.

String extraction in C#

I'm getting pretty frustrated with this, and hope the community can help me out.
I have a string, an example would be "1_ks_Males", another example would be "12_ks_Females".
What I need to do is write a method that extract's each value. So from the first example I'd want something like this:
1
ks
Males
In separate variables.
I'm sure I'm just being incredibly thick, but I just can't get it!
Simply use string.Split('_'). With your input strings it will return a string array with three elements.
You can use Split function for String. Something like this
var split = "1_ks_Males".Split('_');
var first = split[0];
var second = split[1];
var third = split[2];
You just need to use split:
var exampleString = "1_ks_Males";
var split = exampleString.split("_");
var first= split[0]; // 1
var second = split[1]; // ks
var third = split[2]; // Males
string[] array = "1_ks_Males".Split('_');
Assert.AreEqual("1",array[0])
Assert.AreEqual("ks",array[1])
Assert.AreEqual("Males",array[2])
var values = "1_ks_Males".Split('_');
// values[0]: 1
// values[1]: ks
// values[2]: Males
How about this?
var data = myString.Split("_");
var value = data[0];
var #type = data[1];
var gender = data[2];
use String.Split which returns an array of values
var values = "12_ks_Females".split("_");
// values[0] == "12"
// values[1] == "ks"
// values[2] == "Females"
You could use split -
var s = "1_ks_Males";
string[] values = s.Split('_');
Your values will then be contained in the `values' array -
var firstvalue = values[0];
var secondvalue = values[1];
var thirdvalue = values[2];
You'll want to look into the String.Split method of the String class. Here's the MSDN link.
Basically, if all of your strings have the values that you require separated by a consistent character (in your example, this is an underscore character), you can use the Split method which will split a single string into an array of new strings based upon a specific separator.
For example:
string s = "1_ks_Males";
string[] v = s.Split('_');
Console.WriteLine(v[0]);
Console.WriteLine(v[1]);
Console.WriteLine(v[2]);
would output:
1
ks
Males
You should use the String.Split method.
Like: string[] splitParts = "1_ks_Males".Split('_');
This should do the trick:
var values = myString.Split('_');
var splitVar = "1_ks_Males".Split('_');
var firstVar = splitVar[0];
var secondVar = splitVar[1];
var thirdVar = splitVar[2];
Use Split function of the string for it:
var variables = "1_ks_Males".Split(new char[]{'_'}, StringSplitOptions.IgnoreEmpty);
Now variables[0] == "1", variables[1] == "ks", and variables[2] == "Males"
You can use Split function provided by String. Read more about it # MSDN
var data = "1_ks_Males".Split('_');

How to convert char array into int?

I am taking input from a text box. I've saved the input digits from text box to an array like this:
char[] _array = textBox1.Text.ToCharArray(0, textBox1.Text.Length);
Now I want to convert the array to an int array because I want to perform mathematical operations on each index of the array.
How can I achieve the goal?
Thanks.
You could do it with LINQ if you just want the character code of each char.
var intArrayOfText = "some text I wrote".ToCharArray().Select(x => (int)x);
or
var intArrayOfText = someTextBox.Text.ToCharArray().Select(x => (int)x);
If each character expected to be a digit, you can parse it to an int:
List<int> listOfInt = new List<int>();
_array.ToList().ForEach(v => listOfInt.Add(int.Parse(v.ToString())));
int[] _intArray = listOfInt.ToArray();
Character code value:
List<int> listOfCharValue = new List<int>();
_array.ToList().ForEach(v => listOfCharValue.Add((int)v));
int[] _charValueArray = listOfCharValue.ToArray();
You need to handle exceptions.
Assuming what I asked in my comment is true:
string[] ints = { "1", "2", "3" };
var str = ints.Select(i => int.Parse(i));
However, the above will work only if you have already validated that your input from the text box is numeric.
I've solved my problem. I used list to accomplish the task.
I stored each array index at the relative index of the list after converting each index value to int.
Using list seems more convenient way to me. :)
Thanks to all of you.

Categories

Resources