根据每个元素类型过滤集合。
假设您有以下包含整数和字符串元素的列表 -
list.Add("Katie"); list.Add(100); list.Add(200);
过滤集合并仅获取字符串类型的元素。
var myStr = from a in list.OfType<string>() select a;
对于整数类型的工作方式相同。
var myInt = from a in list.OfType<int>() select a;
以下是完整的代码 -
实时演示
using System; using System.Linq; using System.Collections; public class Demo { public static void Main() { IList list = new ArrayList(); list.Add("Katie"); list.Add(100); list.Add(200); list.Add(300); list.Add(400); list.Add("Brad"); list.Add(600); list.Add(700); var myStr = from a in list.OfType<string>() select a; var myInt = from a in list.OfType<int>() select a; Console.WriteLine("Strings..."); foreach (var strVal in myStr) { Console.WriteLine(strVal); } Console.WriteLine("Integer..."); foreach (var intVal in myInt) { Console.WriteLine(intVal); } } }
Strings... Katie Brad Integer... 100 200 300 400 600 700
以上就是C# OfType() 方法的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号