laz
laz

Reputation: 67

c# search arraylist problem

In my code I have an arraylist, called heart, which contains numbers from 1-13.

heart.Add("any");

for(int i = 0; i < 14; i++)
{
    heart.Add(i);
}

As you can see it also contains "any" placed in the first element. When I use this code to get the all of the elements that has a value over 5 I get an error.

int store = heart.Cast<int>().Where(item => item > 5).Count().ToString();

I get the error "Specified cast is not valid" and that's because of the "any" I have in the first element. Could anyone help me fix this?

Upvotes: 0

Views: 387

Answers (5)

FIre Panda
FIre Panda

Reputation: 6637

You could do

Int store = heart.GetRange(1, heart.Count - 1).Cast<int>().Where(item => item > 5).Count().ToString(); 

Upvotes: 0

root
root

Reputation: 1583

Since you're using int and you wanted values of 1-13, may I suggest you use an int value of 0 to represent 'any'?

Upvotes: 0

asawyer
asawyer

Reputation: 17808

You can't cast the word "any" to an integer, that's pretty straight forward.

We'd have to know exactly what your trying to do with here, and how the array is used to really give a good recommendation.

Upvotes: 0

Sven
Sven

Reputation: 22693

Use this instead:

int count = heart.OfType<int>().Count(item => item > 5);

OfType will filter the list and return only those elements that are the correct type, rather than Cast which tries to cast all elements.

Upvotes: 3

Jon Skeet
Jon Skeet

Reputation: 1500835

It sounds like you just need the OfType method instead:

string store = heart.OfType<int>().Where(item => item > 5).Count().ToString();

OfType only returns values which are of the approriate type, ignoring others. See my Edulinq blog post on it for more information.

As Sven shows, you can also use the overload of Count which takes a predicate, to remove the Where call:

string store = heart.OfType<int>().Count(item => item > 5).ToString();

(I've changed the variable type given that you're calling ToString at the end... again, you may want to think about this decision. It depends on how you're using it of course.)

However, I'd strongly advise you to use a strongly-typed collection instead of ArrayList. Think about what the collection is meant to hold - it seems odd to hold both strings and integers. What are you trying to do with it?

Upvotes: 4

Related Questions