Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plain ArrayList Linq c# 2 syntaxes (need a conversion)

Tags:

c#

arraylist

linq

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?

like image 603
user2888973 Avatar asked Dec 31 '25 01:12

user2888973


1 Answers

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; }
}
like image 122
nawfal Avatar answered Jan 01 '26 13:01

nawfal