2016-08-11 5 views
0

入れ子リスト要素があります。そのリストの特定の要素を変更する必要があります。入れ子リスト内の要素を編集する

public List<List<string>> index = new List<List<string>>(); 

このリストから値を変更する必要があります。それがある場合は、私はインデックスを取得する必要があり、その後、値を変更します。

+2

だから質問は何ですか? 'index [3] [2] = ...'は正解です。 –

+0

私はそれが持っている要素を検索し、値を別の値に変更したいと思います。 –

答えて

2

メインリストに反復して、変更したい単語の索引を検索し、見つけたら変更して反復を停止します。

List<List<string>> index = new List<List<string>>(); 
foreach (List<string> list in index) 
{ 
    int i = list.IndexOf("word to search"); 
    if (i >= 0) { 
     list[i] = "new word"; 
     break; 
    } 
} 
1

また、Linqを使用する予定がある場合はselector that also gets the index of the source elementを使用できます。

static bool SearchAndReplace (List<string> strings, string valueToSearch, string newValue) 
    { 
     var found = strings.Select ((s,i)=> new{index=i, val=s}).FirstOrDefault(x=>x.val==valueToSearch); 
     if (found != null) 
     { 
      strings [found.index] = newValue; 
      return true; 
     } 
     return false; 
    } 

    static bool SearchAndReplace (List<List<string>> stringsList, string valueToSearch, string newValue) 
    { 
     foreach (var strings in stringsList) 
     { 
      if (SearchAndReplace(strings, valueToSearch, newValue)) 
       return true; 
     } 
     return false; 

    } 
関連する問題