简单的 ArrayList Linq c# 2 语法(需要转换) [英] Plain ArrayList Linq c# 2 syntaxes (need a conversion)

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

问题描述

这个问题对我来说纯粹是学术性的,是我在这里回答的问题的衍生.

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

从数组列表中检索对象具有特定元素值

这家伙正在使用一个普通的 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?

推荐答案

您可以使用 Cast 将其转换为强类型枚举:

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 如果您的数组列表中有除 Person 之外的任何内容,则会抛出异常.您可以使用 OfType 而不是 Cast 来仅考虑 Person 类型的对象.

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天全站免登陆