1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

C#.NETで配列の一番最後の要素を消す

Last updated at Posted at 2024-02-07

やり方

  • Array.Resize()
  • Linqの Take()

の2つのやり方があります。

サンプルコード
using System;
using System.Linq;

namespace Sampleple
{
    internal class Program
    {
        static void Main(string[] args)
        {
            string[] hai_ = new string[4] {"たきな", "ちさと", "その他", "ほげえええ"};

            //最初の状態
            Console.WriteLine(string.Join(",", hai_));

            //やり方その1
            Array.Resize(ref hai_, hai_.Length - 1);
            Console.WriteLine(string.Join(",", hai_));

            //やり方その2
            hai_ = hai_.Take(hai_.Length - 1).ToArray();
            Console.WriteLine(string.Join(",", hai_));

            Console.ReadLine();
        }
    }
}

実行結果。
image.png

コメント参照

より深い内容まで検討して頂いたコメントがあります。
この記事のコメントも参照下さい。

蛇足

Linqには最後の要素を取得する Last() があるし、参照渡しはあんまりやりたくないから Take() がおススメかな。

参考サイトさん

バージョン

Microsoft .NET Framework Version 4.8.09037

1
1
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?