2013-04-11 36 views
2
 int numPics = 3; //Populated from a query 
     string[] picID = new string[numPics]; 
     //pictureTable is constructed so that it correlates to pictureTable[column][row] 
     string[][] pictureTable = null; //assume the table has data 
     for (int i = 0; i < numPics; i++) 
     { 
      //LINQ query doesn't work. Returns an IEnumerable<string> instead of a string. 
      picID[i] = pictureTable.Where(p => p[0].Equals("ID")).Select(p => p[i]); 
     } 

我是LINQ的新手,但我一直在搜索並沒有找到答案。我希望能夠使用LINQ檢查我的pictureTable中每列的第一個字符串,看看它是否與字符串匹配。然後,我想獲取該列,並從0到i中的每一行提取數據。我知道我可以通過更改列並使行保持不變來實現for循環,但我希望使用LINQ來獲得相同的結果。在鋸齒陣列的所有列中查詢第一個元素

此外,如果有可能擺脫第一個循環,並取得相同的結果,我真的很感興趣,以及。

編輯:可以說我們有一個表格,其中包含以下數據,請記住一切都是字符串。

Column Name [ID] [Name] [Age] 
Row 1   [1] [Jim] [25] 
Row 2   [2] [Bob] [30] 
Row 3   [3] [Joe] [35] 

我希望能夠查詢列名稱,然後能夠通過索引或查詢行數據來從中獲取數據。我會舉一個例子,用for循環來實現我想要的。

 string[][] table = new string[][] { 
           new string[] { "ID", "Name", "Age" }, 
           new string[] { "1", "Jim", "25" }, 
           new string[] { "2", "Bob", "30" }, 
           new string[] { "3", "Joe", "35" }}; 

     string[] resultRow = new string[table.GetLength(1)]; 
     for (int i = 0; i < table.GetLength(0); i++) 
     { 
      if (table[i][0] == "Name") //Given this in a LINQ Query 
      { 
       Console.WriteLine("Column Name = {0}\n", table[i][0]); 
       for (int j = 1; j < table.GetLength(1); j++) //starts at 1 
       { 
        resultRow[i] = table[i][j]; //This is what I want to happen. 
       } 
       break; //exit outer loop 
      } 
     } 
     //Output: 
     //Column Name = Name 
+3

你能提供樣品輸入和所需的輸出嗎? – MarcinJuraszek 2013-04-11 20:59:42

+0

你是什麼意思「從每一行中提取數據」?請準確解釋。 – 2013-04-11 21:52:55

+0

'numPics'是什麼?什麼是picID?你的代碼不完整,問題不清楚。 – 2013-04-11 22:09:53

回答

0

我覺得這會給你的,你在找什麼你resultRow陣列中的其他

string[][] table = new string[][] { 
    new string[] { "ID", "Name", "Age" }, 
    new string[] { "1", "Jim", "25" }, 
    new string[] { "2", "Bob", "30" }, 
    new string[] { "3", "Joe", "35" } 
}; 

//get index of column to look at 
string columnName = "Name"; 
var columnIndex = Array.IndexOf(table[0], columnName, 0); 

// skip the title row, and then skip columns until you get to the proper index and get its value 
var results = table.Skip(1).Select(row => row.Skip(columnIndex).FirstOrDefault()); 

foreach (var result in results) 
{ 
    Console.WriteLine(result); 
} 

有一點要看看會的SelectMany等價,因爲您可以使用它將多個列表拼合成單個列表。

0

你只是想串連在一起的字符串?如果是的話你可以這樣做:

picID[i] = string.Concat(pictureTable.Where(p => p[0].Equals("ID")).Select(p => p[i])); 
+0

雖然這不起作用,但它表示它是IEnumerable ,它不能將其隱式轉換爲字符串。 – TheKobra 2013-04-11 22:24:17