2
3

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 / linq > object[]からHelloを含むstringだけ取得 > var hellos = test.OfType<string>().Where(x => x.Contains("Hello"));

Last updated at Posted at 2015-11-01

Qiitaのコメントにて教えていただいものを元に勉強。

object[]から"Hello"という文字を含むものだけ取得したい。

参考 Keibalight

NG版

test
    .Where(o => o.Contains("Hello"))
    .Select(o => o.ToString())

上記のようにContains()で絞り込もうとしたら以下のようになった。

prog.cs(17,20): error CS1929: Type object' does not contain a member Contains' and the best extension method overload System.Linq.ParallelEnumerable.Contains<string>(this System.Linq.ParallelQuery<string>, string)' requires an instance of type System.Linq.ParallelQuery'

OK版 (注意点あり)

using System;
using System.Linq;

public class Test
{
	public static void Main()
	{
		object[] test = new object[5];
		test[0] = "Hello,Ken";
		test[1] = 3.1415;
		test[2] = "Hello,Taro";
		test[3] = "Hi,Yoko";
		test[4] = 27182;
		
		var hellos = 
		  test
			.Where(o => o != null)
			.Select(o => o.ToString())
			.Where(o => o.Contains("Hello"))
			;

		foreach(var hello in hellos) {
			Console.WriteLine(hello);
		}
	}
}
結果
Success	time: 0.05 memory: 24064 signal:0
Hello,Ken
Hello,Taro

(追記)
ただし、@NetSeed さんのコメントにあるように、本来望まないものを拾ってしまう場合もあるとのこと。
NetSeedさんの方法var hellos = test.OfType<string>().Where(x => x.Contains("Hello"));を使う方がよさそう。

http://ideone.com/WOxBjD
において、

xhellos (OK版)の結果は以下

結果
Success	time: 0.05 memory: 24024 signal:0
Hello,Ken
Hello,Taro
Test+HelloClass

hellos(NetSeedさん版)の結果は以下

結果
Success	time: 0.04 memory: 24016 signal:0
Hello,Ken
Hello,Taro
2
3
2

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
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?