Archive for the ‘LINQ’ tag
文字列の中から数字だけ取り出すには?
ネタ元: 文字列の中から数字だけ取り出すには?
文字列に含まれた複数の数字列を取り出して連結。
もっと簡潔に…書けるかなぁ?
using System;
using System.Linq;
using System.Text.RegularExpressions;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
string text = "あ1いう3え4お56789";
Console.WriteLine(
string.Concat(Regex.Matches(text, @"\d+").Cast().Select(_ => _.Value).ToArray()));
}
}
}
追記: 2010-06-04
Twitter でいくつかフィードバックを貰ったので、再考。
正規表現を使ってないので、この系統の方が性能的には有利なはず。
でも、char[] から string を得るのに string(char []) を使っているところが、ワンライナー的には許せないw
using System;
using System.Linq;
using System.Text.RegularExpressions;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
string text = "あ1いう3え4お56789";
Console.WriteLine(
new string(text.Where(_ => char.IsDigit(_)).ToArray()));
}
}
}
さらに追記: 2010-06-04
お題を消化するだけならコレが最強w
^ による否定をすっかり忘れてたヨ…
あーんど、なんでもかんでも LINQ ろうと思ってはいけないね (^^;
using System;
using System.Text.RegularExpressions;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
string text = "あ1いう3え4お56789";
Console.WriteLine(
Regex.Replace(text, @"[^\d]", string.Empty));
}
}
}
0 から 1000 までに含まれる ‘0’ を数える
ネタ元: gist: 415551 – from http://d.hatena.ne.jp/os0x/20081115/1226770265- GitHub
Sum() しない版。
足し算で「個数を求める」のではなく、「数える」という点を強調したつもり。
あと、ネストをするとラムダ式の引数の名前考えるのがめんどくさい (^^; ので、SelectMany() を使って、早い段階でフラットな IEnumerable に変換してしまっているのもミソ。
using System;
using System.Linq;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(
Enumerable.Range(0, 1001).SelectMany(_ => _.ToString()).Count(_ => _ == '0'));
}
}
}
勝手に競演
ネタ元: 夢の競演みたび
そのままだと面白くないので、複数除外できるようにしてみた。
簡素さを優先するとこんな感じ。excludes を何度も舐めるのが美しくないけど。
result を何度も列挙するような場合、result.ToArray() すればいいよね。
1回しか回さないなら、これでおk。
using System.Linq;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var source = new[]
{
new { Name = "しゅうたん", Type = "アメショ" },
new { Name = "ろり", Type = "アメショ" },
new { Name = "みずきちゃん", Type = "スコティ" },
new { Name = "マグさん", Type = "ほげ" },
new { Name = "?", Type = "もげ" },
};
var excludes = new[] { "ほげ", "もげ" };
var result = source.Where(_ => !excludes.Contains(_.Type));
foreach (var item in result)
{
System.Console.Out.WriteLine("Name = {0}, Type = {1}", item.Name, item.Type);
}
}
}
}