This question already has answers here:
Change strings from one string to another in an array based on a condition
(8 answers)
Closed 9 years ago.
I have an array of strings, most of which are values "true" or "false" some are not and are to remain as are.
I wish to loop through the array and change any "true" or "false" to 1' or zero's
I have kind of started it, but am struggling with the syntax
string[] data = args.Trim().Split(',');
// Loop over strings
foreach (string s in data)
{
if(s == "true")
{
Convert.ToInt32(s)=1;????
}
else if(s == "false")
{
??????
}
}
please can someone offer some guidance
Perhaps with Linq:
string[] data = args.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
.Select(s => StringComparer.OrdinalIgnoreCase.Equals("true", s.Trim()) ? "1"
: StringComparer.OrdinalIgnoreCase.Equals("false", s.Trim()) ? "0" : s)
.ToArray();
Added the StringComparer.OrdinalIgnoreCase to show how you can ignore the case if desired.
Here's a demo with the sample string commented.
this,1,is,not,0
Write a function like this. You can then copy the "converted data" into a new List and return it as an array, or whatever.
public string[] GetData()
{
string[] data = args.Trim().Split(',');
List<string> returnData = new List<string>();
// Loop over strings
foreach (string s in data)
{
if(s == "true"){
returnData.Add("1");
}
else if(s == "false"){
returnData.Add("0");
}
else
returnData.Add(s);
}
return returnData.ToArray();
}
made a presumption you want an array of type string as you don't specify.
Other options as it's unclear what your going to do with the two types of data are to parse the values when you get them out, or split them up into two lists.
string[] rawDatas = GetData();
foreach(string rawData in rawDatas)
{
short iRawData;
if (Int16.TryParse(rawData, out iRawData))
{
if (iRawData == 1 || iRawData == 0)
{
//Add a bit
iRawData;
}
else
{
// add a string
rawData;
}
}
else
{
//add a string
rawData;
}
}
OR
public void GetData(out List<string> strings, out List<Int16> shorts)
{
string[] data = args.Trim().Split(',');
strings= new List<string>();
shorts = new List<Int16>();
// Loop over strings
foreach (string s in data)
{
if(s == "true"){
shorts.Add(1);
}
else if(s == "false"){
shorts.Add(0);
}
else
returnData.Add(s);
}
}
OR
add to an array of object, though this will need casting back on the other side, which is inefficent (see boxing and unboxing)
public object[] GetData()
{
string[] data = args.Trim().Split(',');
List<object> returnData = new List<object>();
// Loop over strings
foreach (string s in data)
{
if(s == "true"){
returnData.Add(1);
}
else if(s == "false"){
returnData.Add(0);
}
else
returnData.Add(s);
}
return returnData.ToArray();
}
if you just want to do 0 and 1 than
string[] data = args.Trim().Split(',');
int[] a = new int[data.length];
// Loop over strings
int count=0;
foreach (string s in data)
{
if(s == "true"){
int a[count] = 1;
}
else if(s == "false"){
int a[count]=0;
}
else
{
a[count] = Convert.ToInt32(s);
}
count++;
}
or with linq
var intlst = data.
Select(input => input == "true" ? 1 :
(input == "false" ? 0 : Convert.ToInt32(input)));
Try this:
var result = data.Select(input => input == "true" ? 1 : (input == "false")? 0 : -1);
You can do this by simple for loop:
List<string> newArgs = new List<string>();
for (int i = 0; i <= args.Length - 1; i++)
{
newArgs.Add(args[i] == "true" ? "1"
: args[i] == "false" ? "0"
: args[i]);
}
Or by using linq which will internally use extension object to iterate through the collection.
Well the problem that I can see you running into is holding the variables themselves without creating a new array. When you type the line
string[] data = args.Trim().Split(',');
you are declaring that the variables within that array are of type string. If you wish to convert them to integers you will need to create a new array of integers or undefined type. I think you are using C# which I believe the code for multiple types in an array is
object[]
In that case you would do something like
object[] data = args.Trim().Split(',');
foreach(string s in data){
if(s == "true"){
s = 1;
Convert.ToInt32(s);
}
else if(s == "false"){
s = 0;
Convert.ToInt32(s);
}
}
Related
How can I convert IList objects to string array?
While working on the telegram bot, some difficulties arose. I get a IList<object> from google table with some information. I need to convert this IList<object> to an array of strings. How can I do this?
static void ReadBudgetTypes()
{
var range = $"{settingsSheet}!B3:B";
var request = service.Spreadsheets.Values.Get(SpreadsheetId, range);
var response = request.Execute();
var values = response.Values; // here i get list of objects from google table
if (values != null && values.Count > 0)
{
foreach (var row in values)
{
Console.WriteLine("{0}", row[0]);
}
}
else
{
Console.WriteLine("No data!");
}
}
Assuming cells may not be strings and may (or may not) have null values, you can print for each cell of the row:
// assumes ToString() gives a meaningful string
var listOfStrings = row.Select(x => x?.ToString()).ToList();
foreach(string cell in listOfStrings)
Console.WriteLine(cell);
or the whole row, joined by a separator
Console.WriteLine(string.Join(", ", row);
If you know the cells are strings you can just cast
var listOfStrings = row.Cast<string>().ToList();
// or
var listOfStrings = row.Select(x => (string)x).ToList();
and then repeat either of the above (loop or string.Join).
If items could be null,
var listOfStrings = row.Select(x => (x ?? (object)"").ToString()).ToList();
you can try this:
var tempList=List<string>();
string[] arrayList=null;
if (values != null && values.Count > 0)
{
foreach (var row in values)
{
tempList.Add(row[0]);
}
arrayList=tempList.ToArray();
}
Try something like this:
IList<object> list = new List<object>(){ "something", "something else" };
string[] array = list.Select(item => (String)item).ToArray();
I recently got asked in a interview to create an method where the following checks are to be made:
Code to check if ArrayList is null
Code to loop through ArrayList objects
Code to make sure object is an integer
Code to check if it is null, and if not then to compare it against a variable containing the smallest integer from the list and if smaller then
overwrite it.
Return the smallest integer in the list.
So I created the following method
static void Main(string[] args)
{
ArrayList list = new ArrayList();
list.Add(1);
list.Add(2);
list.Add(3);
list.Add(4);
list.Add(5);
Program p = new Program();
p.Min(list);
}
private int? Min(ArrayList list)
{
int value;
//Code to check if ArrayList is null
if (list.Count > 0)
{
string minValue = GetMinValue(list).ToString();
//Code to loop through ArrayList objects
for(int i = 0; i < list.Count; i++)
{
//Code to make sure object is an integer
//Code to check if it is null, and if not to compare it against a variable containing the
//smallest integer from the list and if smaller overwrite it.
if (Int32.TryParse(i.ToString(), out value) || i.ToString() != string.Empty)
{
if (Convert.ToInt32(list[i]) < Convert.ToInt32(minValue))
{
minValue = list[i];
}
}
}
}
return Convert.ToInt32(GetMinValue(list));
}
public static object GetMinValue(ArrayList arrList)
{
ArrayList sortArrayList = arrList;
sortArrayList.Sort();
return sortArrayList[0];
}
I think the above is somewhat correct, however am not entirely sure about 4?
I think The following logic may help you. It is simpler than the current and are using int.TryParse() for parsing, which is better than Convert.To..() and int.Parse() Since it has some internal error handling and hence it will will not throw any exception for invalid input. If the input is invalid then it gives 0 to the out variable and returns false, From that we can assume the conversion failed. See the code for this:
var arrayMin = listOfInt;
int currentNum = 0;
int yourNum = int.MaxValue;
bool isSuccess = true;
foreach (var item in listOfInt)
{
if (int.TryParse(item.ToString(), out currentNum) && currentNum <= yourNum)
{
yourNum = currentNum;
}
else
{
isSuccess = false;
break;
}
}
if(isSuccess)
Console.WriteLine("Minimum Number in the array is {0}",yourNum);
else
Console.WriteLine("Invalid input element found");
Simplistic version:
private int? Min(ArrayList list)
{
if (list == null || list.Count == 0) return null;
return list.Cast<int>().Min();
}
I have a string array and it always gives string array length > 0. what is the correct way to check that the string array is not null.
string[] mystr = new string[0];
...
...
if (..) {
mystr = string[] oldstrArray.Clone();
}
...
...
if (mystr[0].Length != 0) {
//Always enters this loop even if mystr is not assigned in the above if condition
}
Try this code snippet:
private static void Main(string[] args)
{
string[] mystr = null;
if (IsNullOrEmpty(mystr))
{
//Do your thing
}
}
static bool IsNullOrEmpty(string[] strarray)
{
return strarray== null || strarray.Length == 0;
}
Or this one (Extension Method)
class MyAwesomeProgram
{
private static void Main(string[] args)
{
string[] mystr = null;
if (mystr.IsNullOrEmpty())
{
//Do what you want
}
}
}
static class Extensions
{
public static bool IsNullOrEmpty(this string[] strarray)
{
return strarray == null || strarray.Length == 0;
}
}
You're asking for the length of the first string in the array, not the array itself. You want to check for mystr.Length instead of mystr[0].Length.
Also, pay attention to the code you're posting - it should compile (LINQPad is very useful for this). Yours has syntax errors, which may hinder people trying to help you.
string[] mystr = new string[] { "", null, "", "", null };
//Check if the array itself is null which is what your question is truly asking
if (mystr == null)
Console.WriteLine("Array is null");
//Check to see if the array itself is empty/zero-length
if (mystr != null && mystr.Length == 0)
Console.WriteLine("Array contains no elements");
//Check if all elements are null or empty
if (mystr != null && mystr.All(s => string.IsNullOrEmpty(s)))
Console.WriteLine("All elements are either null or empty");
if (mystr[0].Length != 0)
It will give you the length of first member of the array. Null check is simple
if(mystr == null)
Length property gives you the size of the array. Length can be used to check empty array
I have a method, I want to be able to verify a string array inside the method. But how would I do it if the string array increase and decrease by the amount of values for example one string might have 2 items, and the next might have 3 items in the string array??
If I have a string that is more than what i have inside the method, i get error: System.IndexOutOfRangeException: Index was outside the bounds of the array.
Here's my method so far:
string1 = "item1, item2";
string2 = "item01, item02, item03";
private void VerifyArrayString(string theString)
{
var elements = theString.Splitnew[] { ',' }, System.StringSplitOptions.RemoveEmptyEntries);
for(int i=0; i<elements.Length; i +=1)
{
if(elements[0] != null)
{
//do something
}
if(elements[1] != null)
{
//do something
}
// and so and so with the next items....
}
}
If you're asking how to make sure you have enough elements for what you're trying to do, you would have to do something like this:
string string1 = "item1, item2";
string string2 = "item01, item02, item03";
private void VerifyArrayString(string theString)
{
var elements = theString.Split(new[] { ',' }, System.StringSplitOptions.RemoveEmptyEntries);
if (elements.Length >= (minimumNumber))
{
for (int i = 0; i < elements.Length; i += 3)
{
if (elements[0] != null)
{
//do something
}
if (elements[1] != null)
{
//do something
}
// and so and so with the next items....
}
}
}
Or if you want to be able to change some numbers and not all, you'd have to go through each one you're changing and make sure you have the right length, such as:
if(elements.Length > 0 && elements[0] != null)
{
//do something
}
//etc etc etc
Revised for clarity:
Based on your comment, you'll want to check your array length each time you're trying to manipulate one of the values of the array. Here is the example code:
string string1 = "item1, item2";
string string2 = "item01, item02, item03";
private void VerifyArrayString(string theString)
{
var elements = theString.Split(new[] { ',' }, System.StringSplitOptions.RemoveEmptyEntries);
for(int i=0; i<elements.Length; i++)
{
if(elements[i] != null)
{
//do something
}
}
}
You can use LINQ to filter with Enumerable.Where:
private void VerifyArrayString(string theString)
{
var elements = theString.Split(new[] { ',' },
StringSplitOptions.RemoveEmptyEntries);
foreach (var element in elements.Where(el => !string.IsNullOrEmpty(el))
{
if (element == "SomeString")
{
// Do Something
}
}
}
This will only yield elements which are not null or an empty string.
I need a way to prepend items on to an existing string array, such that:
string[] dirParams = null;
if (Request.Params["locationDirection_0"] != "")
{
dirParams = Request.Params["locationDirection_0"].Split(',');
}
if (Request.Params["locationDirection_1"] != "")
{
dirParams = Request.Params["locationDirection_1"].Split(',');
}
if (Request.Params["locationDirection_2"] != "")
{
dirParams = Request.Params["locationDirection_2"].Split(',');
}
if (Request.Params["locationDirection_3"] != "")
{
dirParams = Request.Params["locationDirection_3"].Split(',');
}
will give me a string array of about 4 items (assuming none of the requests coming in are empty)
whats the easiest way to do this, I thought of using a list and or a dictonary, neither will work for what I want to do, string array is all I want.
Use a list instead:
List<string> dirParams = new List<string>();
if (Request.Params["locationDirection_0"] != "")
{
dirParams.AddRange(Request.Params["locationDirection_0"].Split(','));
}
if (Request.Params["locationDirection_1"] != "")
{
dirParams.AddRange(Request.Params["locationDirection_1"].Split(','));
}
if (Request.Params["locationDirection_2"] != "")
{
dirParams.AddRange(Request.Params["locationDirection_2"].Split(','));
}
if (Request.Params["locationDirection_3"] != "")
{
dirParams.AddRange(Request.Params["locationDirection_3"].Split(','));
}
Use a List<string> and then the ToArray() method to convert it into a string[].
Build your items in a List<string> then use LINQ's .ToArray () to convert it into an array.
How about using Linq?
var dirParam = Enumerable.Range(0, 4)
.Select(i => Request.Params["locationDirection_" + i])
.Where(s => !String.IsNullOrEmpty(s))
.SelectMany(s => s.Split(','))
.ToArray();