Devdit
 

error CS1061: 'int[]' does not contain a definition for 'Sum' คือ วิธีแก้ไข

0.9K

ต้องการหาผลรวมในตัวแปร Array ของภาษา C# โดยใช้คำสั่ง Sum แต่พอรันแล้วไม่สำเร็จ ขึ้น Error ว่า error CS1061: 'int[]' does not contain a definition for 'Sum' ปัญหานี้ต้องแก้ไขอย่างไร

using System;

class Program
{
    static void Main(string[] args)
    {
        int[] arr = {5, 6, 10, 8, 7};
        int s = arr.Sum();
        Console.Write( "ผลรวมของตัวแปร array คือ "+s );
    }
}

 

วิธีแก้ไข

การใช้คำสั่ง Sum ในภาษา C# เพื่อนับจำนวนข้อมูลใน Array ต้องนำเข้า namespace System.Linq เข้ามาในโค้ดก่อน แนะนำให้เพิ่มคำสั่ง using System.Linq; ไว้ที่ส่วนด้านบนของโค้ด สามารถเขียนโปรแกรมได้ดังนี้

using System;
using System.Linq;

class Program
{
    static void Main(string[] args)
    {
        int[] arr = {5, 6, 10, 8, 7};
        int s = arr.Sum();
        Console.Write( "ผลรวมของตัวแปร array คือ "+s );
    }
}

ผลลัพธ์

ผลรวมของตัวแปร array คือ 36
แก้ไข 2 ปีที่แล้ว
ชอบ
ลิ้งก์
แชร์
Devdit มีช่อง YouTube แล้ว
เราสร้างวิดีโอเกี่ยวกับเทคโนโลยี ทำตามง่ายๆ