普通的ArrayList LINQ的C#语法2(需要转换) [英] Plain ArrayList Linq c# 2 syntaxes (need a conversion)

查看:96
本文介绍了普通的ArrayList LINQ的C#语法2(需要转换)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这问题对我说,我在这里回答一个问题的一个副产品纯学术性的。

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

<一个href=\"http://stackoverflow.com/questions/19469945/retrieve-object-from-an-arraylist-with-a-specific-element-value/19470084#19470084\">Retrieve从ArrayList对象具有特定元素值

这家伙是用普通的ArrayList ......我不知道的最好的事情......充满了人

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;

另一个人提出

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

但是,这似乎并没有工作,因为编译器不能找到p的类型。

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?

推荐答案

您可以使用演员LT; T&GT; 将其转换为一个强类型枚举:

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

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

演员LT; T&GT; 如果你在你的ArrayList以外什么抛出异常。您可以使用 OfType&LT; T&GT; 而不是演员LT; T&GT; 只考虑类型的那些对象

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

这篇关于普通的ArrayList LINQ的C#语法2(需要转换)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆