Mr A
Mr A

Reputation: 6778

Issues With checking int in an array

I am trying to check the int values in an array and based on that do some calculation but the code is not working below is the code:

string EventIds = getVoucher.EventIDs;

int[] array = EventIds.Split(',')
                      .Select(x => int.Parse(x, CultureInfo.InvariantCulture))
                      .ToArray();

if(array.ToString().Any(s => booking.EventID.ToString().Contains(s)))
{do something; } else { do something;}

Upvotes: 0

Views: 87

Answers (5)

Jodrell
Jodrell

Reputation: 35746

Try this,

if (
        EventIds.Split(',').OfType<string>()
            .Any(e => booking.EventID.ToString().Contains(e))
    )
{
    //Some member of a comma delimited list is part of a booking eventID ???
}
else
{
    //Or Not
}

If this is not what you wanted to do then your code is wrong.

EDIT:

After reading you comment I think you want the more logical

If (EventIDs.Split(',').Select(s => 
    int.Parse(s)).OfType<int>().Contains(booking.EventID))
{
    //Ther booking ID is in the list
}
else
{
    //It isn't
}

Upvotes: 1

Sergey K
Sergey K

Reputation: 4114

Why you try to convert to string array?

array.ToString();//???

this code will return System.Int32[]

remove the ToString()!!! if you want to enumerate the array use this code instead

array.AsEnumerable().Any(...

Upvotes: 1

sll
sll

Reputation: 62544

// cache it to avoid multiple time casting
string bookingId = booking.EventID.ToString();

// you can do filtering in the source array without converting it itno the numbers
// as long as you won't have an Exception in case when one of the Ids is not a number
if(EventIds.Split(',').Any(s => bookingId.Contains(s)))
{
  // ..
}
else
{
 // ...
}

Also, depends on how source array is generated you should consider Strign.Trim() to remove spaces:

if(EventIds.Split(',').Any(s => bookingId.Contains(s.Trim())))

Upvotes: 1

Jim Ecker
Jim Ecker

Reputation: 417

Instead of doing a "ToArray()", try doing a "ToList()". you can than use the "Contains" method to search.

Upvotes: 0

dtb
dtb

Reputation: 217401

array.ToString returns the string "System.Int32[]". Using Any with a string checks the predicate for each character in the string.

Assuming that booking.EventID is an int such as 1234, booking.EventID.ToString() returns the string "1234".

So your code checks if "1234" contains any character in "System.Int32[]" (here: true, because "1234" contains the '3' of "System.Int32[]").


You don't say what the desired result is, but I guess you're looking for something like this:

if (array.Any(s => booking.EventID == s))
{
    // ...
}

or

if (Array.IndexOf(array, booking.EventID) != -1)
{
    // ...
}

Upvotes: 3

Related Questions