()selecta; works the same way for integer types. varmyInt=fromainlist.OfType()selecta;The following is the complete code-example real-time demonstration usingSystem;usi"/> ()selecta; works the same way for integer types. varmyInt=fromainlist.OfType()selecta;The following is the complete code-example real-time demonstration usingSystem;usi">

Home  >  Article  >  Backend Development  >  C# OfType() method

C# OfType() method

王林
王林forward
2023-09-23 13:41:081286browse

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);

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

var myStr = from a in list.OfType<string>() select a;

Works the same way for integer types.

var myInt = from a in list.OfType<int>() select a;

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<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);
      }
   }
}

Output

Strings...
Katie
Brad
Integer...
100
200
300
400
600
700

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

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete