2012-05-26 59 views
0

我有一段代碼,我一直在比較2D和1D數組..我可以告訴我如何在另一個2D數組中存儲結果(存在於兩個數組中的元素)? 這裏是代碼 其實我是想在一個新的二維數組SAV「資源」 ......如何在比較後動態添加項目到二維數組? c#窗體

namespace WindowsFormsApplication1strng_cmp 
{ 
    public partial class Form1 : Form 
    { 
     private static Dictionary<string, Position> BuildDict(string[,] symbols) 
     { 
      Dictionary<string, Position> res = new Dictionary<string, Position>(); 
      for (int i = 0; i < symbols.GetLength(0); i++) 
      { 
       for (int j = 0; j < symbols.GetLength(1); j++) 
       { 
        res.Add(symbols[i, j], new Position(i, j)); 
       } 
      } 
      return res; 
     } 

     struct Position 
     { 
      public int x; 
      public int y; 
      public Position(int x, int y) 
      { 
       this.x = x; 
       this.y = y; 
      } 
     } 

     private static List<string> CompareUsingBrute(string[] text, string[,] symbols) 
     { 
      List<string> res = new List<string>(); 
      for (int x = 0; x < symbols.GetLength(0); x++) 
      { 
       for (int y = 0; y < symbols.GetLength(1); y++) 
       { 
        for (int z = 0; z < text.Length; z++) 
        { 
         if (symbols[x, y] == text[z]) 
          res.Add(text[z]); 

        } 

       } 
      } 
      return res; 

     } 
     string[,] symbols = new string[,] { { "if", "else" }, { "for", "foreach" }, { "while", "do" } }; 
     string[] text = new string[] { "for", "int", "in", "if", "then" }; 
     public Form1() 
     { 
      InitializeComponent(); 
     } 

     private void Form1_Load(object sender, EventArgs e) 
     { 

     } 

     private void button1_Click(object sender, EventArgs e) 
     { 
      Dictionary<string, Position> dictionary = BuildDict(symbols); 
      // IndexElement[] index = BuildIndex(symbols); 

      foreach (string s in CompareUsingBrute(text, symbols)) 
      { 
       listBox2.Items.Add("valid"); 
      } 


     } 
    } 
} 
+0

請,你可以打一個比方輸入/輸出? –

回答

0

我明白「從你的問題」是您要比較兩個陣列和存儲的通用元素 -

粘貼了以下輸出作爲圖像 -

class Program 
{ 
    static void Main(string[] args) 
    { 
     String[] array1 = {"a","b","c","d","e","f"}; 
     String[,] array2 = new String[,] {{"a","b","c","d"},{"d","e","f","g"}}; 

     List<String> array1AsList = array1.OfType<String>().ToList(); 
     List<String> array2AsList = array2.OfType<String>().ToList(); 

     // referring from **Ed S comments below**. Instead of using OFType(...) 
     // alternatively you can use the List<>().. ctor to convert an array to list 
     // although not sure for 2D arrays 

     var common = array1AsList.Intersect(array2AsList); 

    } 
} 

enter image description here

+0

爲什麼要撥打'OfType '?它們都是'字符串'數組,因此它們只能保存字符串以開始......另外,還有一個帶有Enumerable的'List '構造函數。 –

+0

將其轉換爲列表。可能是其他方式.. –

+1

'var list = new List (array1);' –