2

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

4
  • 1
    where do you want to put the converted values ? Commented Apr 15, 2013 at 15:37
  • Can you show what is expected output for string "this,true,is,not,false"? Commented Apr 15, 2013 at 15:40
  • I would expect ["this", "1", "is", "not", "0"] Commented Apr 15, 2013 at 15:44
  • Then you want this in the same array? You cannot have both strings and ints in a strongly typed array. You can set the array type to object but then you would need to box / unboxed the types. Commented Apr 15, 2013 at 15:54

6 Answers 6

3

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
Sign up to request clarification or add additional context in comments.

Comments

2

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();
 }

15 Comments

+1: the only answer that actually conforms to the spec. People should spend more time reading and less time frantically cobbling code together in an effort to make a quick post.
@AlexG No actually, OP wants ints not "1" :)
@I4V as stated above, that is not possible in a strongly-typed array. Liam made the reasonable assumption that a string array was wanted. If this is not the case then the OP should clarify.
@Liam yes agree with you there. There are 38 columns in the database5 with a string as their data and the rest are Bit. So all i need to do is get the contents of 'data' into a list that will not care if they are 0's, 1's (Bits maybe?) or indeed strings. Thanks
@Liam for clarification i would like to end up with a array that will hold both strings and Bits (0's & 1's). Then with that mixed bag of bits and strings i would like to assign them one by one to an sql parameter eg: seCmd.Parameters.Add(new SqlParameter("@Supplier", SqlDbType.Bit)); before then actually adding that Bit to the parameter: seCmd.Parameters["@Supplier"].Value = data[1]; and then running the commands Stored procedure. the store procedure will take each of those params and run an update to add the relevant 0's, 1's and strings. Hope that helps clarify :)
|
1

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)));

4 Comments

How do you plan to use a?
... Just edited so no longer valid
@I4V - just updated with all requirement given by OP
@TheKingDave - just updated with all requirement given by OP
0

Try this:

var result = data.Select(input => input == "true" ? 1 : (input == "false")? 0 : -1);

2 Comments

What about not false and not true? (not my downvote)
My downvote - does not do what the question asked: most of which are values "true" or "false" some are not and are to remain as are (admittedly it is quite hard to parse mentally but the code sample backs it up)
0

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.

Comments

-4

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);
    }
}

3 Comments

That won't compile? how can you set string s = 1? and what does Convert.ToInt32(s) do?
-1: this won't compile. C# is strongly-typed, it is not possible to assign an int value to a string variable. Also Convert.ToInt32 is not an in-place operation (it can't be - it is changing types). I would recommend only answering questions in languages that you are familiar with.
-1 - You should probably stop answering C# questions for a while.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.