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 5 years have passed since last update.

csharp > boxing型をJoin > 引数:各要素バージョン / 引数:配列バージョン

Last updated at Posted at 2015-10-29

intやfloat、stringの型が入った配列をJoinしてみる。

boxingを使う。
http://www.atmarkit.co.jp/fdotnet/csharp_abc/csharp_abc_005/csharp_abc03.html

##try1 (引数に個々の要素を指定するバージョン)
http://ideone.com/tSCeoN

using System;

public class Test
{
	public static void Main()
	{
		object []test = new object[5];
		test[0] = (int)1;
		test[1] = (float)3.14;
		test[2] = (string)"Hello!";
		
		string msg;
		msg = string.Join(", ", test[0], test[1], test[2]);
		Console.WriteLine(msg);
	}
}
結果
1, 3.14, Hello!

要素数が可変になる場合はどうするのか未消化。

, test[0], test[1], test[2]の部分をtest[0..2]のような書き方にしたかったがやり方がわからなかった。

try2 (引数に配列を渡すバージョン)

https://msdn.microsoft.com/ja-jp/library/57a79xd0(v=vs.110).aspx
を見て、一旦string[]に入れてからの処理をやってみた。

using System;

public class Test
{
	public static void Main()
	{
		object []test = new object[5];
		test[0] = (int)1;
		test[1] = (float)3.14;
		test[2] = (string)"Hello!";
		
		string [] sArr = new string [5];
		for (int idx=0; idx<3; idx++) {
			sArr[idx] = (test[idx]).ToString();
		}
		
		string msg;
		msg = string.Join(", ", sArr);
		Console.WriteLine(msg);
	}
}
結果
Success	time: 0.04 memory: 23912 signal:0
1, 3.14, Hello!, , 

Joinした時に配列のサイズ(5)まで", "付きになる点は考慮が必要。

##LINQでの処理 (別の配列不要)
別の配列を用意しなくていいエレガントな方法がozwkさんのコメントにあります。

1
1
10

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?