中の技術日誌ブログ

C#とC++/CLIと
VBと.NETとWindowsで戯れる
 

目次

Blog 利用状況

ニュース

自己紹介

東京でソフトウェアエンジニアをやっています。
お仕事大募集中です。
記事執筆や、講師依頼とかでも何でもどうぞ(*^_^*)
似顔絵 MSMVPロゴ
MSMVP Visual C# Since 2004/04-2013/03

記事カテゴリ

書庫

日記カテゴリ

00-整理

01-MSMVP

ジェネリックとは?第3回List<T>.FindAll(Predicate<T>)

第3回List<T>.FindAll(Predicate<T>)

今回はFindAllをはじめとするFind系メソッドだ。

あるArrayListに入っているデータの文字列が、数字の場合に別のArrayListに構築する想定だ。

まずは従来型のソースを見てもらおう。

1.x C#
ArrayList al = new ArrayList();
al.Add("1");
al.Add("B");
al.Add("3");
ArrayList al2 = new ArrayList();
foreach( string text in al)
{
  try
  {
    int.Parse(text);
    al2.Add(text);
  }
  catch
  {
  }
}
1.x VB
Dim al As ArrayList = New ArrayList
al.Add("1")
al.Add("B")
al.Add("3")
Dim al2 As ArrayList = New ArrayList
For Each text As String In al
  Try
    Int32.Parse(text)
    al2.Add(text)
  Catch ex As Exception
  End Try
Next
1.x MC++
ArrayList __gc *al = new ArrayList();
al->Add(S"1");
al->Add(S"B");
al->Add(S"3");
ArrayList __gc *al2 = new ArrayList();
for ( int LoopCounter = 0; LoopCounter < al->Count; LoopCounter++ )
{
  try
  {
    Int32::Parse(static_cast<String*>(al->Item[LoopCounter]));
    al2->Add(static_cast<String*>(al->Item[LoopCounter]));
  }
  catch(Exception*)
  {
  }
}

従来のコーディングであれば、やはり一つ一つArrayListから取り出して評価していくことになる。

この場合取り出すべきデータなのか、そうでないのかというのは例外のキャッチで表現されているので、なんとなくわかるが、true/falseといった形で明確になっていない。

場合によってはExceptionで何か他の例外が発生するのでそれを捕まえるためかと思われてしまう。

2.0 C#
private void button1_Click(object sender, EventArgs e)
{
  List<string> ls = new List<string>();
  ls.Add("1");
  ls.Add("B");
  ls.Add("3");
  Predicate<string> numsel = new Predicate<string>(NumericSelector);
  List<string> ls2 = ls.FindAll(numsel);
}
public bool NumericSelector(string text)
{
  try
  {
    int.Parse(text);
    return true;
  }
  catch (FormatException)
  {
    return false;
  }
}
2.0 VB
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
  Dim ls As List(Of String) = New List(Of String)
  ls.Add("1")
  ls.Add("B")
  ls.Add("3")
  Dim numsel As Predicate(Of String) = New Predicate(Of String)(AddressOf NumericSelector)
  Dim ls2 As List(Of String) = ls.FindAll(numsel)
End Sub
Public Function NumericSelector(ByVal text As String) As Boolean
  NumericSelector = False
  Try
    Int32.Parse(text)
    NumericSelector = True
  Catch ex As Exception
  End Try
End Function
private:
System::Void button1_Click(System::Object^  sender, System::EventArgs^  e)
{
  List<String^>^ ls = gcnew List<String^>();
  ls->Add("1");
  ls->Add("B");
  ls->Add("3");
  Predicate<String^>^ numsel = gcnew Predicate<String^>(this, &Form1::NumericSelector);
  List<String^>^ ls2 = ls->FindAll(numsel);
}
public :
bool NumericSelector(String^ text)
{
  try
  {
    Int32::Parse(text);
    return true;
  }
  catch(Exception^)
  {
    return false;
  }
}

このように一部のデータを抜き出すということ(FindAll)にこのような処理を行うということがより明確になっていると思う。

このPredicateデリゲートは

delegate bool Predicate(<T>)

となっており、YesかNoかの判定に使われる。

List<T>の中で利用されているのは

.Exists
.Find
.FindAll
.FindIndex
.FindLast
.FindListIndex
.RemoveAll
.TrueForAll

と多用されている。

ちなみにArrayにも同様に採用されているので、単純な配列でも同様の処理が可能だ。

おまけの匿名メソッド版の場合には記述が離れた位置にならないため、よりわかりやすい記述になる。

private void button1_Click(object sender, EventArgs e)
{
  List<string> ls = new List<string>();
  ls.Add("1");
  ls.Add("B");
  ls.Add("3");
  List<string> ls2 = ls.FindAll(delegate(string text)
  {
    try
    {
      int.Parse(text);
      return true;
    }
    catch (FormatException)
    {
      return false;
    }
  });
}

連載をまとめてあります。 http://blogs.users.gr.jp/naka/category/285.aspx

 

投稿日時 : 2004年12月5日 0:38

コメントを追加

# re: ジェネリックとは?第3回List&lt;T&gt;.FindAll(Predicate&lt;T&gt;) 2004/12/05 2:50 菊池

Double.TryParse でdoubleでパースしてからint32に変換するほうが例外がらみで遅くなるのを防げますよ。

# re: ジェネリックとは?第3回List&lt;T&gt;.FindAll(Predicate&lt;T&gt;) 2004/12/05 9:57 中 博俊

もちろん2.0ではTryParse君があるのでそちらのほうがいいとして・・・double.TryParse -> Convert.ToInt32の方がいいんですか?
int.TryParseじゃダメ?

# re: ジェネリックとは?第3回List&lt;T&gt;.FindAll(Predicate&lt;T&gt;) 2004/12/05 18:02 菊池

あ、intにもTryParseあったか。
doubleが一番値域が広いのでそこで受けてからオーバーフローチェックとかかける手順を考えてしまいました。
int.TryParseでOKですね。

# vintage alhambra bracelet fake 2017/10/18 4:28 degvlktoqebowefsvaplzbv@hotmal.com

C’est sans doute le meilleur modérateur d’appétit que je connais ?? mais si vous decidez d’acheter anaca3 reducteur d’appétit, n’oubliez pas de boire beaucoup d’eau pour optimiser les effets de ce complément alimentaire
vintage alhambra bracelet fake http://www.howtobuybangles.com/category/fake-van-cleef-and-arpels-bracelet

# rolex oyster perpetual submariner date fake 2017/11/08 3:30 dejhcevhefsmzdkzneic@hotmal.com

Well… they started direct sales of items. Are you happy with them?
rolex oyster perpetual submariner date fake http://www.brandmovement.net/tag/rolex-submariner-replica

# van cleef & arpels alhambra imitation bracelet 2018/04/26 3:12 demjgyhronnovefsterdjjpygbq@hotmal.com

not because you live on a democratic country you will not limit the words that are coming into your mouth. Comedian He is (Vice) but he should restrain and filter the unnecessary words that are coming out to his mouth. Not all people you will please but make it more sound like not offending.
van cleef & arpels alhambra imitation bracelet http://www.perfect-jewelry.nl/

# tadalafil canada order online problems 2021/11/12 22:35 prednisone 5mg

Tadalafil Expedited

# シャネル財布激安 2021/11/22 17:39 zlknjd@live.com

迅速な対応
ありがとうございました。
初めての利用、
写真通りのお品でした。
手書きのお手紙
本物証明書
とーっても丁寧な梱包…
信頼できるお店だと思います。

# ivermectin topical http://stromectolabc.com/
ivermectin 4000 mcg 2022/02/08 3:53 Busjdhj

ivermectin topical http://stromectolabc.com/
ivermectin 4000 mcg

# doxycycline hydrochloride 100mg https://doxycyline1st.com/
doxycycline 50mg 2022/02/25 22:50 Doxycycline

doxycycline hydrochloride 100mg https://doxycyline1st.com/
doxycycline 50mg

# buy doxycycline cheap https://doxycyline1st.com/
doxycycline tetracycline 2022/02/26 10:04 Doxycycline

buy doxycycline cheap https://doxycyline1st.com/
doxycycline tetracycline

# best ed medication https://erectionpills.best/
ed drug prices 2022/06/28 11:24 ErectionPills

best ed medication https://erectionpills.best/
ed drug prices

# writing quotes in an essay b39wad 2022/09/04 7:08 Charlosmox

You actually stated that effectively! https://definitionessays.com/ dissertations writing

# how to write cause and effect essay s83icz 2022/09/08 19:01 Charlosmox


Superb information. With thanks! https://definitionessays.com/ dissertations & theses

# prednisone 60 mg https://prednisone20mg.icu/ 2022/10/15 7:23 Prednisone

prednisone 60 mg https://prednisone20mg.icu/

# asian girl single https://datingtopreview.com/
dating websites 2022/10/17 14:34 Dating

asian girl single https://datingtopreview.com/
dating websites

# non prescription erection pills https://ed-pills.site/
impotence pills 2022/11/17 16:22 EdPills

non prescription erection pills https://ed-pills.site/
impotence pills

# free single site https://datingonlinehot.com/
free and single dating site 2022/12/09 12:11 Dating

free single site https://datingonlinehot.com/
free and single dating site

# best dating https://datingonline1st.com/
pof dating app 2023/01/17 17:43 Dating

best dating https://datingonline1st.com/
pof dating app

# Drug information. Everything information about medication.
https://edonlinefast.com
All trends of medicament. Get information now. 2023/02/17 14:14 EdOnline

Drug information. Everything information about medication.
https://edonlinefast.com
All trends of medicament. Get information now.

# pay to write essay c951ro 2023/02/26 10:58 CharlesSnoff


Whoa plenty of good info.
paying someone to write a paper https://quality-essays.com/ custom essay for sale

# dissertation help co uk review e91oyx 2023/02/27 1:06 Robertsaids


Wonderful postings. Many thanks!
phd dissertation help proposal https://dissertationwritingtops.com/ dissertation help online

# writing a how to essay u80cpp 2023/03/07 18:32 Gregorysaipt


Thanks a lot, Plenty of tips!
how to write a informative essay https://essaywritingservicebbc.com essay writing powerpoint https://writingresearchtermpaperservice.com

# top rated essay writing service z14cid 2023/03/08 16:53 Gregorysaipt


Whoa all kinds of superb data!
final dissertation https://essaypromaster.com how to write a thesis statement for a narrative essay https://englishessayhelp.com

# write a persuasive essay r89iwp 2023/03/08 17:48 EugeneSib


You have made your stand pretty effectively.!
nursing dissertation https://quality-essays.com writing narrative essay https://payforanessaysonline.com

# what to write about in a college essay w80bac 2023/03/10 0:55 EugeneSib

You revealed this effectively.
top ghostwriters https://buycheapessaysonline.com college education essay https://essaywriting4you.com

# assignment writing s73hbj 2023/03/10 15:16 EugeneSib


Perfectly expressed certainly! .
boston college essay https://essaypromaster.com electoral college pros and cons essay https://studentessaywriting.com

# essay writers australia e56dxj 2023/03/11 9:55 Gregorysaipt


Appreciate it, Lots of postings!
essay writing website https://buyanessayscheaponline.com write essays for me https://payforanessaysonline.com

# essay on customer service q69xla 2023/03/13 2:36 EugeneSib


Kudos! Ample data.
dissertation fellowships education https://essaywritingservicebbc.com custom written dissertation https://custompaperwritingservices.com

# best web content writing services j140go 2023/03/13 17:12 EugeneSib

You reported that effectively!
how to write a essay about myself https://essaytyperhelp.com college essay competitions https://helpwritingdissertation.com

# help writing a book k272ey 2023/04/01 16:58 EugeneSib

You expressed this superbly!
how can write essay https://custompaperwritersservices.com college writing service https://homeworkcourseworkhelps.com

# buy cytotec over the counter - https://cytotecsale.pro/# 2023/04/28 13:19 Cytotec

buy cytotec over the counter - https://cytotecsale.pro/#

# over the counter ear wax removal https://overthecounter.pro/# 2023/05/08 13:06 OtcJikoliuj

over the counter ear wax removal https://overthecounter.pro/#

# The plugins developed for WordPress 2023/05/09 23:16 Justas

The plugins developed for WordPress serve to enhance the features and functions of a WordPress website, allowing you to build your awesome and functional site https://t.me/wpigaming/648 Customise WordPress with powerful, professional and intuitive fields.

# prescription drug pricing https://pillswithoutprescription.pro/# 2023/05/15 22:25 PillsPro

prescription drug pricing https://pillswithoutprescription.pro/#

# best treatment for ed https://edpills.ink/# - treatment of ed 2023/07/26 14:34 EdPills

best treatment for ed https://edpills.ink/# - treatment of ed

# п»їfarmacia online migliore 2023/09/25 15:23 Archieonelf

https://farmaciabarata.pro/# farmacia envГ­os internacionales

# versandapotheke 2023/09/26 13:37 Williamreomo

http://onlineapotheke.tech/# online apotheke preisvergleich
online apotheke preisvergleich

# online apotheke deutschland 2023/09/26 15:37 Williamreomo

https://onlineapotheke.tech/# online apotheke deutschland
online apotheke preisvergleich

# farmacia online miglior prezzo 2023/09/26 16:08 Archieonelf

https://pharmacieenligne.icu/# п»?pharmacie en ligne

# gГјnstige online apotheke 2023/09/26 23:38 Williamreomo

https://onlineapotheke.tech/# versandapotheke versandkostenfrei
online apotheke deutschland

# online apotheke gГјnstig 2023/09/27 2:35 Williamreomo

http://onlineapotheke.tech/# versandapotheke deutschland
online apotheke gГ?nstig

# internet apotheke 2023/09/27 3:54 Williamreomo

http://onlineapotheke.tech/# online apotheke versandkostenfrei
versandapotheke

# п»їonline apotheke 2023/09/27 13:10 Williamreomo

https://onlineapotheke.tech/# online apotheke versandkostenfrei
online apotheke gГ?nstig

# comprare farmaci online con ricetta 2023/09/27 19:20 Rickeyrof

acheter sildenafil 100mg sans ordonnance

# п»їonline apotheke 2023/09/27 20:12 Terrywef

acheter sildenafil 100mg sans ordonnance

# farmacie online sicure 2023/09/27 20:42 Rickeyrof

acheter sildenafil 100mg sans ordonnance

# comprare farmaci online all'estero 2023/09/27 22:36 Rickeyrof

acheter sildenafil 100mg sans ordonnance

# ed pills cheap https://edpillsotc.store/# - ed medication online 2023/10/07 16:14 EdPills

ed pills cheap https://edpillsotc.store/# - ed medication online

# best otc ed pills 2023/10/08 6:52 BobbyAtobe

They always keep my medication history well-organized. https://edpillsotc.store/# erection pills

# best non prescription ed pills 2023/10/09 6:52 BobbyAtobe

Their global health insights are enlightening. http://edpillsotc.store/# ed pills gnc

# canadian mail order pharmacies 2023/10/16 14:42 Dannyhealm

They offer the best prices on international brands. https://mexicanpharmonline.shop/# pharmacies in mexico that ship to usa

# mexican drug stores online 2023/10/16 21:52 Dannyhealm

Their commitment to international standards is evident. http://mexicanpharmonline.shop/# mexican mail order pharmacies

# approved canadian pharmacies 2023/10/17 3:08 Dannyhealm

I trust them with all my medication needs. https://mexicanpharmonline.shop/# mexican rx online

# canadian pharnacy 2023/10/17 13:45 Dannyhealm

Love their range of over-the-counter products. https://mexicanpharmonline.com/# mexican border pharmacies shipping to usa

# canadian pharmacies that ship to us 2023/10/17 14:20 Dannyhealm

Their pharmacists are top-notch; highly trained and personable. https://mexicanpharmonline.com/# mexican border pharmacies shipping to usa

# canadian pharamcy 2023/10/17 16:01 Dannyhealm

They make international medication sourcing effortless. https://mexicanpharmonline.com/# mexican mail order pharmacies

# mexico drug stores online 2023/10/17 16:35 Dannyhealm

Their global reach is unmatched. http://mexicanpharmonline.shop/# mexican border pharmacies shipping to usa

# top mail order pharmacies 2023/10/18 3:21 Dannyhealm

Their dedication to global health is evident. http://mexicanpharmonline.shop/# mexican border pharmacies shipping to usa

# canada meds online 2023/10/18 14:21 Dannyhealm

Leading the way in global pharmaceutical services. https://mexicanpharmonline.com/# mexico drug stores pharmacies

# foreign pharmacies com 2023/10/18 19:00 Dannyhealm

Their medication therapy management is top-notch. http://mexicanpharmonline.shop/# mexico drug stores pharmacies

# buy clopidogrel bisulfate https://plavix.guru/ generic plavix 2023/10/23 16:56 Plavixxx

buy clopidogrel bisulfate https://plavix.guru/ generic plavix

# top ed pills 2023/11/20 17:34 WilliamApomb

https://edpills.monster/# ed treatment review

# top rated ed pills 2023/11/23 14:15 WilliamApomb

http://tadalafil.trade/# tadalafil 40 mg online india

# Paxlovid buy online 2023/12/01 3:21 Mathewhip

paxlovid https://paxlovid.club/# Paxlovid buy online

# prescription drug discounts 2023/12/03 6:02 MichaelBum

http://paxlovid.club/# buy paxlovid online

# farmacia online 24 horas 2023/12/07 15:00 RonnieCag

https://tadalafilo.pro/# farmacia online envío gratis

# farmacia envíos internacionales 2023/12/07 18:03 RonnieCag

https://farmacia.best/# farmacia online 24 horas

# farmacias online baratas 2023/12/07 21:18 RonnieCag

http://vardenafilo.icu/# farmacia online

# ï»¿farmacia online 2023/12/08 9:25 RonnieCag

http://farmacia.best/# farmacia 24h

# farmacias baratas online envío gratis 2023/12/08 21:11 RonnieCag

https://tadalafilo.pro/# farmacia online envío gratis

# farmacias online seguras 2023/12/09 12:41 RonnieCag

http://farmacia.best/# farmacias online seguras en españa

# farmacias online seguras en españa 2023/12/09 18:55 RonnieCag

https://farmacia.best/# farmacias baratas online envío gratis

# farmacia online barata 2023/12/09 22:16 RonnieCag

https://vardenafilo.icu/# farmacia online madrid

# farmacia online envío gratis 2023/12/10 14:47 RonnieCag

http://vardenafilo.icu/# farmacias online seguras en españa

# farmacia envíos internacionales 2023/12/11 13:56 RonnieCag

http://tadalafilo.pro/# farmacias online baratas

# farmacia online envío gratis 2023/12/12 15:50 RonnieCag

http://tadalafilo.pro/# farmacias online seguras

# farmacia online envío gratis 2023/12/12 19:18 RonnieCag

http://sildenafilo.store/# sildenafilo 50 mg comprar online

# ï»¿farmacia online 2023/12/13 9:17 RonnieCag

https://sildenafilo.store/# sildenafilo 100mg precio farmacia

# ï»¿farmacia online 2023/12/13 12:18 RonnieCag

https://vardenafilo.icu/# farmacia online madrid

# Pharmacie en ligne livraison 24h 2023/12/14 15:45 Larryedump

http://pharmacieenligne.guru/# Pharmacies en ligne certifiées

# Acheter médicaments sans ordonnance sur internet 2023/12/14 23:48 Larryedump

http://pharmacieenligne.guru/# Pharmacie en ligne fiable

# Pharmacie en ligne France 2023/12/15 3:34 Larryedump

http://pharmacieenligne.guru/# Pharmacie en ligne livraison gratuite

# acheter medicament a l etranger sans ordonnance 2023/12/15 12:57 Larryedump

http://pharmacieenligne.guru/# pharmacie en ligne

# buy prednisone 10mg online https://prednisone.bid/ 100 mg prednisone daily 2023/12/27 2:40 Prednisone

buy prednisone 10mg online https://prednisone.bid/ 100 mg prednisone daily

# purchase doxycycline online 2024/01/06 11:47 BobbyHef

https://cytotec.icu/# buy cytotec online

# ed pills otc 2024/01/09 13:07 CharlesDioky

http://sildenafildelivery.pro/# price sildenafil generic

# can i order cheap clomid pills 2024/01/12 12:04 JeffreyRom

https://paxlovid.guru/# paxlovid covid

# п»їfarmacia online migliore 2024/01/15 20:14 Robertopramy

https://farmaciaitalia.store/# acquisto farmaci con ricetta

# acquistare farmaci senza ricetta 2024/01/16 9:59 Robertopramy

http://tadalafilitalia.pro/# farmacie on line spedizione gratuita

# indian pharmacies safe 2024/01/18 9:53 Jamesspity

http://mexicanpharm.store/# reputable mexican pharmacies online

# can i order generic clomid 2024/01/21 7:55 LarryVoP

Appreciate their commitment to maintaining global healthcare standards https://cytotec.directory/# Abortion pills online

# tamoxifen 20 mg tablet 2024/01/21 14:15 Normantug

https://clomidpharm.shop/# cost of clomid now

# where can i buy clomid without rx 2024/01/22 4:21 AnthonyAnoth

http://prednisonepharm.store/# generic over the counter prednisone

# can you get cheap clomid online 2024/01/22 5:21 LarryVoP

They provide access to global brands that are hard to find locally https://cytotec.directory/# buy cytotec in usa

# Acheter médicaments sans ordonnance sur internet 2024/01/28 1:30 JerryNef

http://pharmadoc.pro/# Pharmacie en ligne livraison 24h

# stromectol south africa 2024/01/29 18:11 Andrewamabs

https://clomiphene.icu/# buy clomid pills

# ivermectin lotion for lice 2024/01/30 9:29 Andrewamabs

https://prednisonetablets.shop/# prednisone acetate

# ivermectin australia 2024/01/30 17:34 Andrewamabs

http://prednisonetablets.shop/# prednisone online for sale

# topical ivermectin cost 2024/01/31 1:58 Andrewamabs

http://prednisonetablets.shop/# buy prednisone online india

# highest rated canadian pharmacies 2024/02/08 22:05 Williamzelia

https://edpill.cheap/# best drug for ed

# zestril cost 2024/02/22 4:00 Charlesmax

https://furosemide.guru/# lasix for sale

# compare zestril prices 2024/02/24 3:37 Charlesmax

http://buyprednisone.store/# prednisone over the counter south africa

# on line dating services 2024/03/03 12:09 Thomasjax

https://lanarhoades.fun/# lana rhoades video

# connecting singles games 2024/03/04 4:06 RodrigoGrany

https://sweetiefox.online/# swetie fox

# dating naked 2024/03/04 9:48 Thomasjax

https://evaelfie.pro/# eva elfie

# dating apps 2024/03/05 7:26 Thomasjax

https://sweetiefox.online/# sweeti fox

# lesbian cowgirls 2024/03/07 1:49 HowardBox

naked dating: http://miamalkova.life/# mia malkova hd

# dating near me free 2024/03/07 17:22 HowardBox

pof dating login: https://miamalkova.life/# mia malkova videos

# single women dating 2024/03/10 3:40 HowardBox

best dating website in usa: https://lanarhoades.pro/# lana rhoades videos

# melhor jogo de aposta para ganhar dinheiro 2024/03/14 2:51 BrianTop

https://jogodeaposta.fun/# aviator jogo de aposta

# gates of olympus demo 2024/03/28 13:01 KeithNaf

http://aviatoroyna.bid/# aviator oyna slot

# can i purchase clomid without insurance 2024/04/03 4:56 Robertsuela

https://prednisoneall.shop/# 20mg prednisone

# buying generic clomid 2024/04/04 12:59 Robertsuela

http://clomidall.com/# cost generic clomid for sale

# cost cheap clomid without insurance 2024/04/04 17:08 Robertsuela

https://prednisoneall.com/# prednisone 10mg prices

# diflucan generic price 2024/04/14 15:57 Josephfep

http://stromectola.top/# where to buy ivermectin cream

タイトル
名前
URL
コメント