2013-04-11 83 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