在 C# 中过滤数组 [英] filter an array in C#
本文介绍了在 C# 中过滤数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个对象数组(例如 Car[])并且对象上有一个 IsAvailable 属性
i have an array of objects (Car[] for example) and there is an IsAvailable Property on the object
我想使用完整数组(其中 IsAvailable 对于某些项目为 true,对于其他一些项目为 false)作为输入并返回一个新数组,其中仅包含 IsAvailable = true 的项目.
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...
using System.Linq;
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屋!
查看全文