按字符串值过滤2D String矩阵的行

时间:2015-01-06 15:56:35

标签: c# .net arrays linq jagged-arrays

所以我有一个定义为String[][] data_set_examples的二维数组,其中包含以下数据:

Sunny,Hot,High,Weak,No
Sunny,Hot,High,Strong,No
Overcast,Hot,High,Weak,Yes
Rain,Mild,High,Weak,Yes
Rain,Cool,Normal,Weak,Yes
...

我想按特定值过滤行,例如包含" Hot"的行。 (按列索引1)

我理解一种可能性是使用LINQ。虽然我不熟悉,但我尝试了以下内容,但是没有进行过滤。

var result = from u in data_set_examples
                         where u[column_index].Equals(attribute_value)
                         select u;
我做错了什么?还有另一种方法吗?

2 个答案:

答案 0 :(得分:1)

您的代码看起来很好,我认为问题在于检查过滤结果。

使用时

foreach (string[] s in result) 
{ 
    Console.WriteLine(s); 
}

您只是在写string[]

的类型名称

但是你应该看到结果中的string[]内的string[][]

你可以用两种方式做到这一点

foreach (string[] s in result)
{
     //concatenate all the values in s
     Console.WriteLine(string.Join(",", s));
}

foreach (string[] s in result)
{
    //iterate through strings in s and print them
    foreach (string s1 in s)
    {
        Console.Write(s1 + " ");
    }
    Console.WriteLine();
}

答案 1 :(得分:1)

我试过这个,并且确认它有效:

 string[][] data_set_examples = new string[][]{
                new string[]{"Sunny", "Hot", "High", "Weak", "No"},
                new string[]{"Sunny", "Hot", "High", "Strong", "No"},
                new string[]{"Overcast", "Hot", "High", "Weak", "Yes"},
                new string[]{"Rain", "Mild", "High", "Weak", "Yes"},
                new string[]{"Rain", "Cool", "Normal", "Weak", "Yes"},
            };
            IEnumerable<string[]> result = from u in data_set_examples
                         where u[1].Equals("Hot")
                         select u;
            foreach (string[] s in result) {
                foreach (string part in s)
                    Console.Write(part + " ");
                Console.WriteLine();
            }
            Console.Read();

制作输出:

Sunny Hot High Weak No
Sunny Hot High Strong No
Overcast Hot High Weak Yes