3

This question is purely academic for me and a spinoff of a question I answered here.

Retrieve object from an arraylist with a specific element value

This guy is using a plain ArrayList... I Know not the best thing to do ... filled with persons

class Person
    {
        public string Name { get; set; }
        public string Gender { get; set; }

        public Person(string name, string gender)
        {
            Name = name;
            Gender = gender;
        }
    }

personArrayList = new ArrayList();

personArrayList.Add(new Person("Koen", "Male"));
personArrayList.Add(new Person("Sheafra", "Female"));

Now he wants to select all females. I solve this like this

var females = from Person P in personArrayList where P.Gender == "Female" select P;

Another guy proposes

var persons = personArrayList.AsQueryable();
var females = persons.Where(p => p.gender.Equals("Female"));

But that does not seem to work because the compiler can never find out the type of p.

Does anyone know what the correct format for my query would be in the second format?

3 Answers 3

3

You can use Cast<T> to cast it to a strongly typed enumerable:

var females = personArrayList.Cast<Person>()
                             .Where(p => p.gender.Equals("Female"));

Cast<T> throws exception if you have anything other than Person in your arraylist. You can use OfType<T> instead of Cast<T> to consider only those objects of type Person.

On a side note, kindly use an enum for gender, not strings.

enum Sex { Male, Female }

class Person
{
    public Sex Gender { get; set; }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Right, I was just wondering and threw together an example to show my question... of course we should use an enum but since this was a bad example to start with ....
@user2888973 Yes so bad that you started with an ArrayList :P Dont forget to accept answers which helped you the most.
2

Since the ArrayList has untyped members, you'll have to cast the members to Person:

var females = persons.OfType<Person>().Where(p => p.gender.Equals("Female"));

2 Comments

The first does not work. (Compiler error no where for arraylist) The second does work just fine
@user2888973 strange, I don't know why. Anyway, thanks, I removed the first since it's wrong.
1

Cast personArrayList to its element type and you are done.

var persons = personArrayList.Cast<Person>();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.