用 C# 編寫程式查詢列表中元素的立方


使用 Select 方法和 Lambda 表示式計算元素的立方。

以下為我們的列表。

List<int> list = new List<int> { 2, 4, 5, 7 };

現在,使用 Select() 方法並計算立方。

list.AsQueryable().Select(c => c * c * c);

以下是完整示例。

示例

 現場演示

using System;
using System.Linq;
using System.Collections.Generic;
public class Demo {
   public static void Main() {
      List<int> list = new List<int> { 2, 4, 5, 7 };
      Console.WriteLine("Elements...");
      // initial list javascript:void(0)
      foreach (int n in list)
      Console.WriteLine(n);
      // cube of each element
      IEnumerable<int> res = list.AsQueryable().Select(c => c * c * c);
      Console.WriteLine("Cube of each element...");
      foreach (int n in res)
      Console.WriteLine(n);
   }
}

輸出

Elements...
2
4
5
7
Cube of each element...
8
64
125
343

更新日期:2020 年 6 月 23 日

482 次瀏覽

開啟你的職業生涯

完成課程以獲得認證

開始
廣告
© . All rights reserved.