问题
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