VB 2008のList(Of 構造体またはクラス)について、もうひとつ質問させてください。
※前回の質問
http://madia.world.coocan.jp/cgi-bin/vbnet/wwwlng.cgi?print+200907/09070014.txt
例えば、構造体Stru1があるとします。Stru1のメンバにはValue1とValue2(いずれもStringとする)があるとします。
そして、List(Of Stru1)というリストを作成したとします。このListに含まれるStru1構造体の中で、
Stru1.Value2の値が"hogehoge"であるものが存在するかどうかを簡単に調べる方法はあるでしょうか?
もしあるならばどのようにすればよいか、お教え頂きたく、よろしくお願いします。
また、今後の勉強のために、例えばListに含まれるStru1構造体の中で、Stru1.Value2の値が"hogehoge"である構造体が、
Listの何番目にあるか(インデックスの値)を簡単に調べる方法についてもアドバイス頂けると大変ありがたいです。
よろしくお願いします。
とりあえず、List(Of T) メンバ
http://msdn.microsoft.com/ja-jp/library/d9hw1as6.aspx?ppud=4
から検索とかインデックスとか関係しそうなメソッドを調べてみたらどうでしょう。
Existsメソッドとか。
MSDN: List(T).Exists メソッド (System.Collections.Generic)
http://msdn.microsoft.com/ja-jp/library/bfed8bca.aspx
'Dim srcList As New List(Of Stru1)()
Dim targetValue As String = "hogehoge"
'≪A:該当する Stru1 を 1 つ取得≫
'Find メソッド
' 複数該当する場合は、最初に一致した Stru1 構造体。
' 該当項目が無い時は、空の Stru1 構造体。
Dim dstFirstStru1 As Stru1 = srcList.Find(Function(x) x.Value2 = targetValue)
'FindLast メソッド
' 複数該当する場合は、最後に一致する Stru1 構造体。
' 該当項目が無い時は、空の Stru1 構造体。
Dim dstLastStru1 As Stru1 = srcList.FindLast(Function(x) x.Value2 = targetValue)
'≪B:該当する Stru1 をすべて取得≫
'FindAll メソッド
Dim dstList As List(Of Stru1) = srcList.FindAll(Function(x) x.Value2 = targetValue)
'≪C:該当する Index を 1 つ取得≫
'FindIndex メソッド
' 複数該当する場合は、最初に一致した Index。
' 該当項目が無い時は、-1 。
Dim dstFirstIndex As Integer = srcList.FindIndex(Function(x) x.Value2 = targetValue)
'FindLastIndex メソッド
' 複数該当する場合は、最後に一致する Index。
' 該当項目が無い時は、-1 。
Dim dstLastIndex As Integer = srcList.FindLastIndex(Function(x) x.Value2 = targetValue)
'≪D:該当する Index をすべて取得≫
'ループ処理以外では、こんな方法しか思いつかず…。
Dim dstAllIndices() As Integer = (From x In srcList.Select(Function(y, i) New With {y, i}) Where x.y.Value2 = targetValue Select x.i).ToArray()
'≪E:該当する物があるかどうかを判定≫
'Exists メソッド、または Any 拡張メソッド
Dim hasData As Boolean = srcList.Exists(Function(x) x.Value2 = targetValue)
'≪F:すべての項目が該当しているかどうかを判定≫
'All 拡張メソッド
Dim isAll As Boolean = srcList.All(Function(x) x.Value2 = targetValue)
みなさま、ご回答ありがとうございました。
感謝いたします。
色々と勉強していきたいと思います。
今後ともよろしくお願いいたします。
ぜんぜんわからんな。
通りすがりはA級に解決できません。
tourisugari as List(of point)=new List(ofr point)()
この変がわかりません。
ツイート | ![]() |