过滤器在C#中的数组 [英] filter an array in C#

查看:128
本文介绍了过滤器在C#中的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有对象的数组(车[]为例),并有一个IsAvailable属性的对象

i have an array of objects (Car[] for example) and there is an IsAvailable Property on the object

我想使用的全阵列(其中IsAvailable为一些物品真假一些其他)作为输入,并返回一个新的数组,其包括仅具有IsAvailable =真

i want to use the full array (where IsAvailable is true for some items and false for some others) as the input and return a new array which includes only the items that have IsAvailable = true.

推荐答案

如果您正在使用C#3.0或更高...

If you're using C# 3.0 or better...

public Car[] Filter(Car[] input)
{
    return input.Where(c => c.IsAvailable).ToArray();
}

如果你没有访问LINQ(您使用的是旧版本的.NET)...

And if you don't have access to LINQ (you're using an older version of .NET)...

public Car[] Filter(Car[] input)
{
    List<Car> availableCars = new List<Car>();

    foreach(Car c in input)
    {
        if(c.IsAvailable)
            availableCars.Add(c);
    }

    return availableCars.ToArray();
}

这篇关于过滤器在C#中的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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