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
Related
First of all sorry for the question if it sounds stupid (just started programming), and im not very good at english.
So, i want to make a while loop that activates when a var is neither any of 4 string values.
something like this:
while(var != ["str1", "str2", "str3", "str4"]){
And i would like to know how to write it, or another way to do it.
thanks.
If your strings are hardcoded, the "dumb" way to do this is:
while (var != "str1" && var != "str2"...) {
If the strings are part of a collection, you could likely use collection.Contains(var) or something like that.
Another way is an extension method:
public static bool In<T>(this T t, params T[] array)
{
for (int i = 0; i < array.Length; i++)
{
if (t.Equals(array[i]))
{
return true;
}
}
return false;
}
Then you could just do var.In("str1", "str2", "str3", "str4").
I think with Linq you could accomplish something like this:
var invalid = new string[]{ "str1", "str2", "str3", "str4"};
var value = Console.ReadLine();
while(!invalid.Contains(value))
{
// whatever you need inside the loop
}
As you as you are new to programming
while(condition1 && condition2 && ....) would be clear.
But if the no of strings increases exponentially than
write a function that return true or false and call that as condition for while loop
ex bool function(val)
{
//SOS
return true only if not equal to all the strings
else
return false
}
and in while loop
while(function(v))
is neither any of 4 string values
Actually this can be almost literally translated into linq C# code:
string [] set = new string[]{ "str1", "str2", "str3", "str4"};
while (!set.Any(x => x == myValue))
{
// ...
}
The easiest way to do this would be:
class Program
{
static void Main(string[] args)
{
Console.WriteLine("--Start--");
Console.WriteLine("Enter value:");
var x = Console.ReadLine();
while(x != "a" && x != "b" && x != "c" && x != "d")
{
Console.WriteLine("Try again");
x = Console.ReadLine();
}
Console.WriteLine("--End--");
Console.Read();
}
}
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 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 have a NameValueCollection in a usercontrol that is initialized like so:
private NameValueCollection _nameValues = HttpUtility.ParseQueryString(Request.QueryString.ToString());
When I call the ToString() on this it generates a proper querystring which I can use for an updated url.
However, when I copy the NameValueCollection via its constructor like so:
var nameValues = new NameValueCollection(_nameValues);
And then try to form an url:
var newUrl = String.Concat(_rootPath + "?" + nameValues.ToString());
It outputs an url like this:
"http://www.domain.com?System.Collections.Specialized.NameValueCollection"
How can I copy a NameValueCollection so that the ToString() method outputs desired results?
The problem is there are two actual types in your code. The fist one is System.Web.HttpValueCollection which has it's ToString method overriden to get the result you expect and the second one is System.Collection.Specialized.NameValueCollection which does not override ToString. What you can do, if you really need to use System.Collection.Specialized.NameValueCollection is to create an extension method.
public static string ToQueryString(this NameValueCollection collection)
{
var array = (from key in collection.AllKeys
from value in collection.GetValues(key)
select string.Format("{0}={1}", HttpUtility.UrlEncode(key), HttpUtility.UrlEncode(value))).ToArray();
return "?" + string.Join("&", array);
}
and use it:
var newUrl = String.Concat(_rootPath,nameValues.ToQueryString());
It is not NameValueCollection that provides the string formatting. That functionality is in an internal class System.Web.HttpValueCollection that is returned by HttpUtility.ParseQueryString.
So you will not be able to achieve this behavior by using built in functionality. Your best bet would be to create an extension method that formats the values in a URL format.
Here is the method from HttpValueCollection class - you might be able to use it with some modifications.
// System.Web.HttpValueCollection
internal virtual string ToString(bool urlencoded, IDictionary excludeKeys)
{
int count = this.Count;
if (count == 0)
{
return string.Empty;
}
StringBuilder stringBuilder = new StringBuilder();
bool flag = excludeKeys != null && excludeKeys["__VIEWSTATE"] != null;
for (int i = 0; i < count; i++)
{
string text = this.GetKey(i);
if ((!flag || text == null || !text.StartsWith("__VIEWSTATE", StringComparison.Ordinal)) && (excludeKeys == null || text == null || excludeKeys[text] == null))
{
if (urlencoded)
{
text = HttpValueCollection.UrlEncodeForToString(text);
}
string value = (text != null) ? (text + "=") : string.Empty;
string[] values = this.GetValues(i);
if (stringBuilder.Length > 0)
{
stringBuilder.Append('&');
}
if (values == null || values.Length == 0)
{
stringBuilder.Append(value);
}
else
{
if (values.Length == 1)
{
stringBuilder.Append(value);
string text2 = values[0];
if (urlencoded)
{
text2 = HttpValueCollection.UrlEncodeForToString(text2);
}
stringBuilder.Append(text2);
}
else
{
for (int j = 0; j < values.Length; j++)
{
if (j > 0)
{
stringBuilder.Append('&');
}
stringBuilder.Append(value);
string text2 = values[j];
if (urlencoded)
{
text2 = HttpValueCollection.UrlEncodeForToString(text2);
}
stringBuilder.Append(text2);
}
}
}
}
}
return stringBuilder.ToString();
}
internal static string UrlEncodeForToString(string input)
{
return HttpUtility.UrlEncodeUnicode(input);
}
Calling .ToString() on a name value collection will just give you the namespace it belongs to.
I suspect you want the key and value out of it, Assuming that it's the first in the collection why not just do:
var newUrl = String.Concat(_rootPath + "?" + nameValues.GetKey(0) + nameValues.Get(0));
You can have this as an extension method:
public static string ToString(this NameValueCollection nvc, int idx)
{
if(nvc == null)
throw new NullReferenceException();
string key = nvc[idx];
if(nvc.HasKeys() && !string.IsNullOrEmpty(key))
{
return string.Concat(key, nvc.Get(key)); //maybe want some formatting here
}
return string.Empty;
}
Usage:
NameValueCollection nvc = new NameValueCollection();
string foo = nvc.ToString(0); //gets key + value at index 0
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);
}
}