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

╄→гoц情女王★ 提交于 2019-12-23 20:50:53

问题


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?


回答1:


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



回答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"));



回答3:


Cast personArrayList to its element type and you are done.

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


来源:https://stackoverflow.com/questions/19470731/plain-arraylist-linq-c-sharp-2-syntaxes-need-a-conversion

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!