C# OfType() method

王林
Release: 2023-09-23 13:41:08
forward
1218 people have browsed it

C# OfType() 方法

Filter the collection based on each element type.

Suppose you have the following list containing integer and string elements -

list.Add("Katie");
list.Add(100);
list.Add(200);
Copy after login

Filter the collection and get only the elements of string type.

var myStr = from a in list.OfType() select a;
Copy after login

Works the same way for integer types.

var myInt = from a in list.OfType() select a;
Copy after login

The following is the complete code -

Example

Real-time demonstration

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() select a;
      var myInt = from a in list.OfType() select a;
      Console.WriteLine("Strings...");
      foreach (var strVal in myStr) {
         Console.WriteLine(strVal);
      }
      Console.WriteLine("Integer...");
      foreach (var intVal in myInt) {
         Console.WriteLine(intVal);
      }
   }
}
Copy after login

Output

Strings...
Katie
Brad
Integer...
100
200
300
400
600
700
Copy after login

The above is the detailed content of C# OfType() method. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!